Pandemonium

Typical random-related functions for JavaScript and TypeScript.

README

Pandemonium


Pandemonium is a dead simple JavaScript/TypeScript library providing typical random-related functions such as choice, sample etc.

The library also provides a way to create any of the available functions using a custom random source (seedrandom, for instance).

Installation


  1. ```
  2. npm install --save pandemonium
  3. ```

Usage


Summary


_Typical helpers_


_Sampling_

n being the number of items in the sampled sequence and k being the number of items to be sampled.

MethodTimeMemoryNote
-------------------------------------------------------------------------------------------------------------------------------------------------------
[dangerouslyMutatingSample](#dangerouslymutatingsample)`O(k)``O(k)`Must
[fisherYatesSample](#fisheryatessample)`O(n)``O(n)`Probably
[geometricReservoirSample](#geometricreservoirsample)`O(k*log(n/k))``O(k)`Probably
[naiveSample](#naivesample)`Ω(k)`,`O(k)`Only
[reservoirSample](#reservoirsample)`O(n)``O(k)`Useful
[sampleWithReplacements](#samplewithreplacements)`O(k)``O(k)`Performant
[samplePairs](#samplepairs)`Ω(k)`,`O(k)`Variant
[sampleOrderedPairs](#sampleorderedpairs)`Ω(k)`,`O(k)`Variant
[weightedReservoirSample](#weightedreservoirsample)`O(n)``O(k)`Variant

choice


Function returning a random item from the given array.

  1. ```js
  2. import choice from 'pandemonium/choice';
  3. // Or
  4. import {choice} from 'pandemonium';

  5. choice(['apple', 'orange', 'pear']);
  6. >>> 'orange'

  7. // To create your own function using custom RNG
  8. import {createChoice} from 'pandemonium/choice';

  9. const customChoice = createChoice(rng);
  10. ```

random


Function returning a random integer between given a & b.

  1. ```js
  2. import random from 'pandemonium/random';
  3. // Or
  4. import {random} from 'pandemonium';

  5. random(3, 7);
  6. >>> 4

  7. // To create your own function using custom RNG
  8. import {createRandom} from 'pandemonium/random';

  9. const customRandom = createRandom(rng);
  10. ```

randomBoolean


Function returning a random boolean.

  1. ```js
  2. import randomBoolean from 'pandemonium/random-boolean';
  3. // Or
  4. import {randomBoolean} from 'pandemonium';

  5. randomBoolean();
  6. >>> true

  7. // To create your own function using custom RNG
  8. import {createrandomBoolean} from 'pandemonium/random-boolean';

  9. const customRandomBoolean = createRandomBoolean(rng);
  10. ```

randomFloat


Function returning a random float between given a & b.

  1. ```js
  2. import randomFloat from 'pandemonium/random-float';
  3. // Or
  4. import {randomFloat} from 'pandemonium';

  5. randomFloat(-5, 55);
  6. >>> 6.756482

  7. // To create your own function using custom RNG
  8. import {createRandomFloat} from 'pandemonium/random-float';

  9. const customRandomFloat = createRandomFloat(rng);
  10. ```

randomIndex


Function returning a random index of the given array.

  1. ```js
  2. import randomIndex from 'pandemonium/random-index';
  3. // Or
  4. import {randomIndex} from 'pandemonium';

  5. randomIndex(['apple', 'orange', 'pear']);
  6. >>> 1

  7. // Alternatively, you can give the array's length instead
  8. randomIndex(3);
  9. >>> 2

  10. // To create your own function using custom RNG
  11. import {createRandomIndex} from 'pandemonium/random-index';

  12. const customRandomIndex = createRandomIndex(rng);
  13. ```

randomString


Function returning a random string.

  1. ```js
  2. import randomString from 'pandemonium/random-string';
  3. // Or
  4. import {randomString} from 'pandemonium';

  5. // To generate a string of fixed length
  6. randomString(5);
  7. >>> 'gHepM'

  8. // To generate a string of variable length
  9. randomString(3, 7);
  10. >>> 'hySf3'

  11. // To create your own function using custom RNG
  12. import {createRandomString} from 'pandemonium/random-string';

  13. const customRandomString = createRandomString(rng);

  14. // If you need a custom alphabet
  15. const customRandomString = createRandomString(rng, 'ATGC');
  16. ```

randomUint32


Function returning a random unsigned 32bits number.

  1. ```js
  2. import {randomUint32} from 'pandemonium/random-typed-int';
  3. // Or
  4. import {randomUint32} from 'pandemonium';

  5. randomUint32();
  6. >>> 397536

  7. // To create your own function using custom RNG
  8. import {createRandomUint32} from 'pandemonium/random-typed-int';

  9. const customRandomUint32 = createRandomUint32(rng);
  10. ```

randomPair


Function returning a random pair from the given array.

Note that this function will return unordered pairs (i.e. [0, 1] and [1, 0] are to be considered the same) and will not return pairs containing twice the same item (i.e. [0, 0]).

  1. ```js
  2. import randomPair from 'pandemonium/random-pair';
  3. // Or
  4. import {randomPair} from 'pandemonium';

  5. randomPair(['apple', 'orange', 'pear', 'cherry']);
  6. >>> ['orange', 'cherry']

  7. // Alternatively, you can give the array's length instead and get a pair of indices
  8. randomPair(4);
  9. >>> [1, 3]

  10. // To create your own function using custom RNG
  11. import {createRandomPair} from 'pandemonium/random-pair';

  12. const customRandomPair = createRandomPair(rng);
  13. ```

randomOrderedPair


Function returning a random ordered pair (i.e. [0, 1] won't be considered to be the same as [1, 0]) from the given array.

  1. ```js
  2. import randomOrderedPair from 'pandemonium/random-ordered-pair';
  3. // Or
  4. import {randomOrderedPair} from 'pandemonium';

  5. randomOrderedPair(['apple', 'orange', 'pear', 'cherry']);
  6. >>> ['cherry', 'apple']

  7. // Alternatively, you can give the array's length instead and get a pair of indices
  8. randomOrderedPair(4);
  9. >>> [3, 0]

  10. // To create your own function using custom RNG
  11. import {createRandomOrderedPair} from 'pandemonium/random-ordered-pair';

  12. const customRandomPair = createRandomOrderedPair(rng);
  13. ```

shuffle


Function returning a shuffled version of the given array using the Fisher-Yates algorithm.

If what you need is to shuffle the original array in place, check out [shuffleInPlace](#shuffleinplace).

  1. ```js
  2. import shuffle from 'pandemonium/shuffle';
  3. // Or
  4. import {shuffle} from 'pandemonium';

  5. shuffle(['apple', 'orange', 'pear', 'pineapple']);
  6. >>> ['pear', 'orange', 'apple', 'pineapple']

  7. // To create your own function using custom RNG
  8. import {createShuffle} from 'pandemonium/shuffle';

  9. const customShuffle = createShuffle(rng);
  10. ```

shuffleInPlace


Function shuffling the given array in place using the Fisher-Yates algorithm.

  1. ```js
  2. import shuffleInPlace from 'pandemonium/shuffle-in-place';
  3. // Or
  4. import {shuffleInPlace} from 'pandemonium';

  5. const array = ['apple', 'orange', 'pear', 'pineapple'];
  6. shuffleInPlace(array);

  7. // Array was mutated:
  8. array >>> ['pear', 'orange', 'apple', 'pineapple'];

  9. // To create your own function using custom RNG
  10. import {createShuffleInPlace} from 'pandemonium/shuffle-in-place';

  11. const customShuffleInPlace = createShuffleInPlace(rng);
  12. ```

weightedChoice


Function returning a random item from the given array of weights.

Note that weights don't need to be relative.

  1. ```js
  2. import weightedChoice from 'pandemonium/weighted-choice';
  3. // Or
  4. import {weightedChoice} from 'pandemonium';

  5. const array = [.1, .1, .4, .3, .1];
  6. weightedChoice(array);
  7. >>> .4

  8. // To create your own function using custom RNG
  9. import {createWeightedChoice} from 'pandemonium/weighted-choice';

  10. const customWeightedChoice = createWeightedChoice(rng);

  11. // If you have an array of objects
  12. const customWeightedChoice = createWeightedChoice({
  13.   rng: rng,
  14.   getWeight: (item, index) => {
  15.     return item.weight;
  16.   }
  17. });

  18. const array = [{fruit: 'pear', weight: 4}, {fruit: 'apple', weight: 30}];
  19. customWeightedChoice(array);
  20. >>> 'apple'


  21. // If you intent to call the function multiple times on the same array,
  22. // you should use the cached version instead:
  23. import {createCachedWeightedChoice} from 'pandemonium/weighted-choice';

  24. const array = [.1, .1, .4, .3, .1];
  25. const customWeightedChoice = createCachedWeightedChoice(rng, array);

  26. customWeightedChoice();
  27. >>> .3
  28. ```

weightedRandomIndex


Function returning a random index from the given array of weights.

Note that weights don't need to be relative.

  1. ```js
  2. import weightedRandomIndex from 'pandemonium/weighted-random-index';
  3. // Or
  4. import {weightedRandomIndex} from 'pandemonium';

  5. const array = [.1, .1, .4, .3, .1];
  6. weightedRandomIndex(array);
  7. >>> 2

  8. // To create your own function using custom RNG
  9. import {createWeightedRandomIndex} from 'pandemonium/weighted-random-index';

  10. const customWeightedRandomIndex = createWeightedRandomIndex(rng);

  11. // If you have an array of objects
  12. const customWeightedRandomIndex = createWeightedRandomIndex({
  13.   rng: rng,
  14.   getWeight: (item, index) => {
  15.     return item.weight;
  16.   }
  17. });

  18. const array = [{fruit: 'pear', weight: 4}, {fruit: 'apple', weight: 30}];
  19. customWeightedRandomIndex(array);
  20. >>> 1


  21. // If you intent to call the function multiple times on the same array,
  22. // you should use the cached version instead:
  23. import {createCachedWeightedRandomIndex} from 'pandemonium/weighted-random-index';

  24. const array = [.1, .1, .4, .3, .1];
  25. const customWeightedRandomIndex = createCachedWeightedRandomIndex(rng, array);

  26. customWeightedRandomIndex();
  27. >>> 3
  28. ```

dangerouslyMutatingSample


Function returning a random sample of size k from the given array.

This function runs in O(k) time & memory but is somewhat dangerous because it will mutate the given array while performing its Fisher-Yates shuffle before reverting the mutations at the end.

  1. ```js
  2. import dangerouslyMutatingSample from 'pandemonium/dangerously-mutating-sample';
  3. // Or
  4. import {dangerouslyMutatingSample} from 'pandemonium';

  5. dangerouslyMutatingSample(2, ['apple', 'orange', 'pear', 'pineapple']);
  6. >>> ['apple', 'pear']

  7. // To create your own function using custom RNG
  8. import {createDangerouslyMutatingSample} from 'pandemonium/dangerously-mutating-sample';

  9. const customSample = createDangerouslyMutatingSample(rng);
  10. ```

fisherYatesSample


Function returning a random sample of size k from the given array.

This function uses a partial Fisher-Yates shuffle and therefore runs in O(k) time but must clone the given array to work, which adds O(n) time & memory.

  1. ```js
  2. import fisherYatesSample from 'pandemonium/fisher-yates-sample';
  3. // Or
  4. import {fisherYatesSample} from 'pandemonium';

  5. fisherYatesSample(2, ['apple', 'orange', 'pear', 'pineapple']);
  6. >>> ['apple', 'pear']

  7. // To create your own function using custom RNG
  8. import {createFisherYatesSample} from 'pandemonium/fisherYatesSample';

  9. const customFisherYatesSample = createFisherYatesSample(rng);
  10. ```

geometricReservoirSample


Function returning a random sample of size k from the given array.

This function runs in O(k * (1 + log(n / k))) time & O(k) memory using "Algorithm L" taken from the following paper:

Li, Kim-Hung. "Reservoir-sampling algorithms of time complexity O(n (1+ log (N/n)))." ACM Transactions on Mathematical Software (TOMS) 20.4 (1994): 481-493.


Note that this function is able to sample indices without requiring you to represent the range of indices in memory.

  1. ```js
  2. import geometricReservoirSample from 'pandemonium/geometric-reservoir-sample';
  3. // Or
  4. import {geometricReservoirSample} from 'pandemonium';

  5. geometricReservoirSample(2, ['apple', 'orange', 'pear', 'pineapple']);
  6. >>> ['apple', 'pear']

  7. // Alternatively, you can pass a length and get a sample of indices back
  8. geometricReservoirSample(2, 4);
  9. >>> [0, 2]

  10. // To create your own function using custom RNG
  11. import {createGeometricReservoirSample} from 'pandemonium/geometric-reservoir-sample';

  12. const customSample = createGeometricReservoirSample(rng);
  13. ```

naiveSample


Function returning a random sample of size k from the given array.

This function works by keeping a Set of the already picked items and choosing a random item in the array until we have the desired k items.

While it is a good pick for cases when k is little compared to the size of your array, this function will see its performance drop really fast when k becomes proportionally bigger.

Note that this function is able to sample indices without requiring you to represent the range of indices in memory.

  1. ```js
  2. import naiveSample from 'pandemonium/naive-sample';
  3. // Or
  4. import {naiveSample} from 'pandemonium';

  5. naiveSample(2, ['apple', 'orange', 'pear', 'pineapple']);
  6. >>> ['apple', 'pear']

  7. // Alternatively, you can pass a length and get a sample of indices back
  8. naiveSample(2, 4);
  9. >>> [0, 2]

  10. // To create your own function using custom RNG
  11. import {createNaiveSample} from 'pandemonium/naive-sample';

  12. const customSample = createNaiveSample(rng);
  13. ```

reservoirSample


Function returning a random sample of size k from the given array.

This function runs in O(n) time and O(k) memory.

A helper class able to work on an arbitrary stream of data that does not need to fit into memory is also available if you need it.

  1. ```js
  2. import reservoirSample from 'pandemonium/reservoir-sample';
  3. // Or
  4. import {reservoirSample} from 'pandemonium';

  5. reservoirSample(2, ['apple', 'orange', 'pear', 'pineapple']);
  6. >>> ['apple', 'pear']

  7. // To create your own function using custom RNG
  8. import {createReservoirSample} from 'pandemonium/reservoir-sample';

  9. const customReservoirSample = createReservoirSample(rng);

  10. // To use the helper class
  11. import {ReservoirSampler} from 'pandemonium/reservoir-sample';

  12. // If RNG is not provided, will default to Math.random
  13. const sampler = new ReservoirSampler(10, rng);

  14. for (const value of lazyIterable) {
  15.   sampler.process(value);
  16. }

  17. // To retrieve the sample once every value has been consumed
  18. const sample = sampler.end();
  19. ```

sampleWithReplacements


Function returning a random sample of size k with replacements from the given array. This prosaically means that an items from the array might occur several times in the resulting sample.

The function runs in both O(k) time & space complexity.

  1. ```js
  2. import sampleWithReplacements from 'pandemonium/sample-with-replacements';
  3. // Or
  4. import {sampleWithReplacements} from 'pandemonium';

  5. sampleWithReplacements(3, ['apple', 'orange', 'pear', 'pineapple']);
  6. >>> ['apple', 'pear', 'apple']

  7. // To create your own function using custom RNG
  8. import {createSampleWithReplacements} from 'pandemonium/sample-with-replacements';

  9. const customSample = createSampleWithReplacements(rng);
  10. ```

samplePairs


Function returning a random sample of k unique unordered pairs from the given array.

It works by storing a unique key created from the picked pairs, making it a specialized variant of naiveSample.

It is usually quite efficient because when sampling pairs, the total size of the population, being combinatorial, is often magnitudes larger than the size of the sample we need to retrieve.

Note finally that this function is able to sample pairs of indices without requiring you to represent the range of indices in memory.

  1. ```js
  2. import samplePairs from 'pandemonium/sample-pairs';
  3. // Or
  4. import {samplePairs} from 'pandemonium';

  5. samplePairs(2, ['apple', 'orange', 'pear', 'pineapple']);
  6. >>>  [['apple', 'pear'], ['orange', 'pear']]

  7. // Alternatively, you can pass a length and get a sample of pairs of indices
  8. samplePairs(2, 4);
  9. >>> [[0, 2], [1, 2]]

  10. // To create your own function using custom RNG
  11. import {createSamplePairs} from 'pandemonium/sample-pairs';

  12. const customSamplePairs = createSamplePairs(rng);
  13. ```

sampleOrderedPairs


Function returning a random sample of k unique ordered pairs from the given array.

It works by storing a unique key created from the picked pairs, making it a specialized variant of naiveSample.

It is usually quite efficient because when sampling pairs, the total size of the population, being combinatorial, is often magnitudes larger than the size of the sample we need to retrieve.

Note finally that this function is able to sample pairs of indices without requiring you to represent the range of indices in memory.

  1. ```js
  2. import sampleOrderedPairs from 'pandemonium/sample-pairs';
  3. // Or
  4. import {sampleOrderedPairs} from 'pandemonium';

  5. sampleOrderedPairs(2, ['apple', 'orange', 'pear', 'pineapple']);
  6. >>>  [['apple', 'pear'], ['pear', 'orange']]

  7. // Alternatively, you can pass a length and get a sample of pairs of indices
  8. sampleOrderedPairs(2, 4);
  9. >>> [[0, 2], [2, 1]]

  10. // To create your own function using custom RNG
  11. import {createSampleOrderedPairs} from 'pandemonium/sample-ordered-pairs';

  12. const customSampleOrderedPairs = createSampleOrderedPairs(rng);
  13. ```

weightedReservoirSample


Function returning a random sample of size k from a given array of weighted items.

The result is a sample without replacement, which, in the case of weighted items, has been chosen to mean that subsequent items are picked based on the proportional total weight of the remaining items.

We use algorithm "A-ES" from the following papers:

Pavlos S. Efraimidis, Paul G. Spirakis. "Weighted random sampling with a reservoir." https://arxiv.org/pdf/1012.0256.pdf


Pavlos S. Efraimidis. "Weighted Random Sampling over Data Streams."


This function runs in O(n) time and O(k) memory.

A helper class working able to work on an arbitrary stream of data that does not need to fit into memory is also available if you need it.

  1. ```js
  2. import weightedReservoirSample from 'pandemonium/weighted-reservoir-sample';
  3. // Or
  4. import {weightedReservoirSample} from 'pandemonium';

  5. weightedReservoirSample(2, [.1, .1, .4, .3, .05]);
  6. >>> [.3, .4]

  7. // To create your own function using custom RNG
  8. import {createWeightedReservoirSample} from 'pandemonium/weighted-reservoir-sample';

  9. const customWeightedReservoirSample = createWeightedReservoirSample(rng);

  10. // To sample arbitrary items
  11. const data = [{label: 'orange', importance: 34}, ...];

  12. const customWeightedReservoirSample = createWeightedReservoirSample({
  13.   getWeight: item => item.importance
  14. });

  15. // To use the helper class
  16. import {WeightedReservoirSampler} from 'pandemonium/weighted-reservoir-sample';

  17. // If RNG is not provided, will default to Math.random
  18. const sampler = new WeightedReservoirSampler(10, {rng, getWeight});

  19. for (const value of lazyIterable) {
  20.   sampler.process(value);
  21. }

  22. // To retrieve the sample once every value has been consumed
  23. const sample = sampler.end();
  24. ```

Contribution


Contributions are obviously welcome. Please be sure to lint the code & add the relevant unit tests before submitting any PR.

  1. ```
  2. git clone git@github.com:Yomguithereal/pandemonium.git
  3. cd pandemonium
  4. npm install

  5. # To lint the code
  6. npm run lint

  7. # To run the unit tests
  8. npm test
  9. ```

License