diff --git a/docs/reference/random.rst b/docs/reference/random.rst index 21a1b5c55..eed470b52 100644 --- a/docs/reference/random.rst +++ b/docs/reference/random.rst @@ -42,12 +42,13 @@ In practice of course, you'll probably be randomly generating more useful inform :returns: A shuffled copy of the input ``array``. - .. js:function:: constrainedShuffle(array, constraints, [helpers={}, maxIterations=10**4]) + .. js:function:: constrainedShuffle(array, constraints, [helpers={}, maxIterations=10**4, failOnMaxIterations=false]) :param array array: Array to be shuffled :param constraints: Constraint specification as an object, or a check function (see below) :param object helpers: Optional specification of ``equality`` check or ``hash`` function used while checking constraints. :param int maxIterations: Maximum number of shuffle iterations to go through before giving up. + :param Boolean failOnMaxIterations: If max iterations are reached, throws an exception if true, else warns in the console. :returns: A shuffled copy of the input ``array``, subject to specified constraints. diff --git a/packages/library/src/util/random/index.js b/packages/library/src/util/random/index.js index a4c093413..974f38bfe 100644 --- a/packages/library/src/util/random/index.js +++ b/packages/library/src/util/random/index.js @@ -139,7 +139,7 @@ export class Random { return array } - constrainedShuffle(a, constraints={}, helpers={}, maxIterations=10**4) { + constrainedShuffle(a, constraints={}, helpers={}, maxIterations=10**4, failOnMaxIterations=false) { // Generate constraint function, if necessary let constraintChecker if (isFunction(constraints)) { @@ -168,7 +168,12 @@ export class Random { if (constraintChecker(candidate)) break } if (i >= maxIterations) { - console.warn(`constrainedShuffle could not find a matching candidate after ${ maxIterations } iterations`) + const warning = `constrainedShuffle could not find a matching candidate after ${ maxIterations } iterations` + if (failOnMaxIterations) { + throw new Error(warning) + } else { + console.warn(warning) + } } return candidate }