npm.io
5.0.6 • Published 1 week ago

alea-deck

Licence
MIT
Version
5.0.6
Deps
2
Size
12 kB
Vulns
0
Weekly
0
Stars
1

alea-deck

Uniform and weighted shuffling and sampling, just like deck, but utilizing Alea instead of Math.random.

Example

import { shuffle, pick } from 'alea-deck';

shuffle([1, 2, 3, 4]);
// => [1, 4, 2, 3]

pick([1, 2, 3, 4]);
// => 2

shuffle({
  a: 10,
  b: 8,
  c: 2,
  d: 1,
  e: 1
});
// => ['b', 'a', 'c', 'd', 'e']

pick({
  a: 10,
  b: 8,
  c: 2,
  d: 1,
  e: 1
});
// => a

Installation

$ npm install alea-deck

API

import { deck, shuffle, pick, normalize } from 'alea-deck';
deck(collection)

Binds shuffle and pick to collection, returning an object with both methods pre-applied.

const d = deck([1, 2, 3, 4]);

d.shuffle(); // => [3, 1, 4, 2]
d.pick();    // => 3
shuffle(collection)

If collection is an Array, returns a new shuffled Array based on a unifrom distributionm without mutating the original Array.

Otherwise, if collection is an Object, returns a new shuffled Array of collection's visible keys based on the value weights of collection.

pick(collection)

Samples collection without mutating collection.

If collection is an Array, returns a random element from collection with a uniform distribution.

Otherwise, if collection is an Object, returns a random key from collection biased by its normalized value.

normalize(obj)

Return a new obj Object where the values have been divided by the sum of all the values such that the sum of all the values in the returned Object is 1.

If any weights are < 0, an Error is thrown.

Keywords