repl.it
@KrofDrakula/

safeRandom

Nodejs

Just an example of a subtle bug in a naive implementation of "integer between 0 and n"

fork
loading
Files
  • index.js
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const naiveRandom = max => Math.floor(Math.random() * max);

const safeRandom = max => Math.floor(Math.random() * (max + 1 - Number.EPSILON));

const spread = (fn, max, samples = 1000) =>
  new Array(samples).fill(0).map(() => fn(max)).reduce((counts, n) => {
    counts[n] = (counts[n] || 0) + 1;
    return counts;
  }, [])

const naiveTest = spread(naiveRandom, 10, 10000);
const safeTest = spread(safeRandom, 10, 10000);

console.log(naiveTest.map((n,i) => `${i} => ${n}`));
console.log(safeTest.map((n,i) => `${i} => ${n}`));
node v10.16.0