Skip to content

Commit 9e0ac43

Browse files
authored
deterministic shuffling (#190)
fixes #189 note: shuffling is here to increase performance (#83)
1 parent cfbdb22 commit 9e0ac43

File tree

3 files changed

+27
-2
lines changed

3 files changed

+27
-2
lines changed

src/array.js

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,19 @@
1+
import lcg from "./lcg.js";
2+
13
export default function(x) {
24
return typeof x === "object" && "length" in x
35
? x // Array, TypedArray, NodeList, array-like
46
: Array.from(x); // Map, Set, iterable, string, or anything else
57
}
68

79
export function shuffle(array) {
8-
var m = array.length,
10+
const random = lcg();
11+
let m = array.length,
912
t,
1013
i;
1114

1215
while (m) {
13-
i = Math.random() * m-- | 0;
16+
i = random() * m-- | 0;
1417
t = array[m];
1518
array[m] = array[i];
1619
array[i] = t;

src/lcg.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// https://en.wikipedia.org/wiki/Linear_congruential_generator#Parameters_in_common_use
2+
const a = 1664525;
3+
const c = 1013904223;
4+
const m = 4294967296; // 2^32
5+
6+
export default function() {
7+
let s = 1;
8+
return () => (s = (a * s + c) % m) / m;
9+
}

test/pack/deterministic-test.js

Lines changed: 13 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)