Skip to content
This repository has been archived by the owner on Nov 22, 2022. It is now read-only.

Commit

Permalink
Add fail option to constrainedShuffle
Browse files Browse the repository at this point in the history
  • Loading branch information
dgfitch authored and FelixHenninger committed Aug 22, 2020
1 parent e928ae1 commit 82f9de8
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
3 changes: 2 additions & 1 deletion docs/reference/random.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
9 changes: 7 additions & 2 deletions packages/library/src/util/random/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down Expand Up @@ -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
}
Expand Down

0 comments on commit 82f9de8

Please sign in to comment.