pick-random-weighted

    1.2.3 • Public • Published

    pick-random-weighted

    NPM Build Status codebeat badge Coverage Status XO code style

    Simple, fast and lightweight function to pick a random element from a weighted array.

    Install

    npm install pick-random-weighted

    Usage

    const pick = require('pick-random-weighted');
     
    const colors = [
        ['Red', 30],
        ['Green', 20],
        ['Blue', 40]
    ];
     
    const color = pick(colors);

    pick(values)

    Returns a value.

    values

    Type: Array

    List of values to pick from.

    Each element should be provided in the format [value, weight].

    Random number generation

    By default, and to keep a small footprint, the library uses Math.random() to generate the random number to pick the value.

    If you need you can define a custom function to generate random values, you can create a function that returns fixed values to use on your unit tests or implement a more specialized library like random-js.

    Using a custom random generator

    By overwriting pick.random you can define your custom function.

    Remember the returned value should be a number within the [0,1) range.

    const pick = require('pick-random-weighted');
     
    pick.random = function () {
        return 0.3;
    };
     
    const colors = [
        ['Red', 30],
        ['Green', 20],
        ['Blue', 40]
    ];
     
    const color = pick(colors);
    // Will always return 'Green'

    Install

    npm i pick-random-weighted

    DownloadsWeekly Downloads

    306

    Version

    1.2.3

    License

    MIT

    Unpacked Size

    5.86 kB

    Total Files

    7

    Last publish

    Collaborators

    • alvarocastro