hange-random-weight
TypeScript icon, indicating that this package has built-in type declarations

1.0.3 • Public • Published

hange-random-weight

Randomly pick an array item by weight callback

Usage

import random from 'hange-random-weight'
let items = [
    {
        name: 'Alex',
        weight: 1,
        count: 0
    },
    {
        name: 'Jonny',
        weight: 2,
        count: 0
    },
    {
        name: 'Tom',
        weight: 3,
        count: 0
    },
    {
        name: 'Lily',
        weight: 2,
        count: 0
    },
    {
        name: 'John',
        weight: 1,
        count: 0
    },
    {
        name: 'Rebecca',
        weight: 1,
        count: 0
    }
]
const ITERATION = 1000000
for (let i = 0; i < ITERATION; i++) {
    let w = random(items, i => i.weight)
    w.count++
}
for (let i = 0; i < items.length; i++) {
    console.log(`${items[i].name}: ${(items[i].count / ITERATION * 100).toFixed(2)}%`)
}

Readme

Keywords

none

Package Sidebar

Install

npm i hange-random-weight

Weekly Downloads

1

Version

1.0.3

License

ISC

Unpacked Size

17.2 kB

Total Files

8

Last publish

Collaborators

  • hangu32