random-weighted-pick 1.0.12 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.circleci/config.yml +1 -1
- package/.eslintrc.json +7 -0
- package/.prettierrc +4 -0
- package/CONTRIBUTING.md +9 -0
- package/README.md +144 -45
- package/dist/cjs/index.js +43 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/weightList.js +166 -0
- package/dist/esm/index.d.ts +4 -0
- package/dist/esm/index.js +5 -0
- package/dist/esm/weightList.d.ts +36 -0
- package/dist/esm/weightList.js +161 -0
- package/jest.config.cjs +5 -0
- package/package.json +22 -32
- package/tsconfig.cjs.json +8 -0
- package/tsconfig.esm.json +8 -0
- package/tsconfig.json +20 -0
- package/.eslintrc +0 -27
- package/coverage/clover.xml +0 -54
- package/coverage/coverage-final.json +0 -3
- package/coverage/lcov-report/base.css +0 -212
- package/coverage/lcov-report/index.html +0 -106
- package/coverage/lcov-report/prettify.css +0 -1
- package/coverage/lcov-report/prettify.js +0 -1
- package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
- package/coverage/lcov-report/sorter.js +0 -158
- package/coverage/lcov-report/src/index.html +0 -93
- package/coverage/lcov-report/src/utils/index.html +0 -93
- package/coverage/lcov-report/src/utils/tests.utils.js.html +0 -128
- package/coverage/lcov-report/src/weightList.js.html +0 -194
- package/coverage/lcov.info +0 -106
- package/dist/index.js +0 -1
- package/scripts/emptyFolder.js +0 -18
- package/webpack.config.js +0 -46
- package/webpack.prod.config.js +0 -31
package/.circleci/config.yml
CHANGED
package/.eslintrc.json
ADDED
package/.prettierrc
ADDED
package/CONTRIBUTING.md
ADDED
package/README.md
CHANGED
|
@@ -1,81 +1,180 @@
|
|
|
1
1
|
# random-weighted-pick
|
|
2
|
-
A lightweight utility that allows you to easily choose a random item from a weighted list of items, with a probability dependent on their weight.
|
|
3
2
|
|
|
4
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/random-weighted-pick)
|
|
4
|
+
[](https://www.npmjs.com/package/random-weighted-pick)
|
|
5
|
+
[](https://bundlephobia.com/package/random-weighted-pick)
|
|
6
|
+

|
|
7
|
+

|
|
8
|
+

|
|
9
|
+

|
|
10
|
+
[](./LICENSE)
|
|
5
11
|
|
|
6
|
-
|
|
12
|
+
Lightweight utility to pick random items from a weighted list, with probability proportional to each item's weight. Zero external deps. MIT licensed.
|
|
7
13
|
|
|
8
|
-
|
|
14
|
+
## Installation
|
|
9
15
|
|
|
16
|
+
```bash
|
|
17
|
+
npm install random-weighted-pick
|
|
18
|
+
```
|
|
10
19
|
|
|
11
|
-
|
|
12
|
-
|
|
20
|
+
- **Node**: `>=16`
|
|
21
|
+
- Supports **ESM** and **CommonJS**.
|
|
13
22
|
|
|
14
|
-
|
|
15
|
-
npm i -S random-weighted-pick
|
|
16
|
-
```
|
|
23
|
+
## Import
|
|
17
24
|
|
|
18
|
-
|
|
25
|
+
```ts
|
|
26
|
+
// ESM
|
|
27
|
+
import weightedPick, { pickMany, createWeightedPicker } from 'random-weighted-pick'
|
|
19
28
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
//
|
|
23
|
-
var weightedPick = require('random-weighted-pick');
|
|
29
|
+
// CommonJS
|
|
30
|
+
// const { weightedPick, pickMany, createWeightedPicker } = require('random-weighted-pick')
|
|
31
|
+
// or: const weightedPick = require('random-weighted-pick')
|
|
24
32
|
```
|
|
25
33
|
|
|
26
|
-
|
|
34
|
+
## Quick start
|
|
27
35
|
|
|
36
|
+
```ts
|
|
28
37
|
const options = [
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
38
|
+
{ id: 0, weight: 0.2, item: () => 'Lemon' },
|
|
39
|
+
{ id: 1, weight: 0.3, item: ['Grape', 'Orange', 'Apple'] },
|
|
40
|
+
{ id: 2, weight: 0.4, item: 'Mango' },
|
|
41
|
+
{ id: 3, weight: 0.1, item: 3 },
|
|
33
42
|
]
|
|
34
|
-
// Sum of 'weights' should be equal 1.
|
|
35
43
|
|
|
36
|
-
|
|
44
|
+
// Weights are normalized automatically (sum does not need to be 1)
|
|
45
|
+
const one = weightedPick(options)
|
|
46
|
+
console.log(one) // { id: 2, item: 'Mango' }
|
|
47
|
+
|
|
48
|
+
// Pick multiple (with replacement by default)
|
|
49
|
+
const many = pickMany(options, 2)
|
|
50
|
+
|
|
51
|
+
// Pick multiple without replacement
|
|
52
|
+
const noReplacement = pickMany(options, 2, { replacement: false })
|
|
37
53
|
|
|
38
|
-
|
|
54
|
+
// Efficient picker for many selections (alias method by default)
|
|
55
|
+
const picker = createWeightedPicker(options, { method: 'alias' })
|
|
56
|
+
const next = picker.pick() // { id, item }
|
|
39
57
|
```
|
|
40
|
-
[🔄 **Run this example on Codepen**](https://codepen.io/phellipeandrade/pen/NyyNrX)
|
|
41
58
|
|
|
42
|
-
##
|
|
43
|
-
### install
|
|
44
|
-
`npm install`
|
|
59
|
+
## API
|
|
45
60
|
|
|
46
|
-
|
|
47
|
-
|
|
61
|
+
### `weightedPick(options, config?) => { id: number, item: T }`
|
|
62
|
+
Pick 1 item according to its weight.
|
|
48
63
|
|
|
49
|
-
`
|
|
64
|
+
### `pickMany(options, k, config?) => Array<{ id: number, item: T }>`
|
|
65
|
+
Pick `k` items. When `replacement: false`, sampling is without replacement.
|
|
50
66
|
|
|
51
|
-
|
|
67
|
+
### `createWeightedPicker(options, config?)`
|
|
68
|
+
Create an optimized picker for multiple selections.
|
|
52
69
|
|
|
53
|
-
|
|
70
|
+
Returns an object with:
|
|
71
|
+
- `pick(): { id: number, item: T }`
|
|
72
|
+
- `pickMany(k: number): Array<{ id: number, item: T }>`
|
|
73
|
+
- `updateWeight(id: number, weight: number): void` — updates an item's weight and rebuilds internal structures.
|
|
54
74
|
|
|
55
|
-
|
|
75
|
+
## Types
|
|
56
76
|
|
|
57
|
-
|
|
77
|
+
```ts
|
|
78
|
+
export interface WeightedInput<T> {
|
|
79
|
+
id?: number
|
|
80
|
+
weight: number
|
|
81
|
+
item: T
|
|
82
|
+
}
|
|
58
83
|
|
|
59
|
-
|
|
60
|
-
|
|
84
|
+
export interface WeightedResult<T> {
|
|
85
|
+
id: number
|
|
86
|
+
item: T
|
|
87
|
+
}
|
|
61
88
|
|
|
62
|
-
|
|
89
|
+
export type RNG = () => number
|
|
63
90
|
|
|
64
|
-
|
|
91
|
+
export interface PickConfig {
|
|
92
|
+
normalize?: boolean // default: true
|
|
93
|
+
epsilon?: number // default: 1e-12
|
|
94
|
+
rng?: RNG // default: crypto.getRandomValues (when available) or Math.random
|
|
95
|
+
}
|
|
65
96
|
|
|
66
|
-
|
|
97
|
+
export type Method = 'cdf' | 'alias'
|
|
98
|
+
```
|
|
67
99
|
|
|
68
|
-
|
|
100
|
+
- `pickMany` also accepts `{ replacement?: boolean }`.
|
|
101
|
+
- `createWeightedPicker` accepts `{ method?: 'cdf' | 'alias' }`.
|
|
69
102
|
|
|
70
|
-
|
|
103
|
+
## Options and behavior
|
|
71
104
|
|
|
72
|
-
`
|
|
105
|
+
- **Normalization**: `normalize: true` by default. Weights are normalized to sum to 1. If `normalize: false`, the sum of weights must be 1 (± `epsilon`).
|
|
106
|
+
- **RNG**: defaults to `crypto.getRandomValues` when available; otherwise `Math.random`. You can inject a custom RNG.
|
|
107
|
+
- **Method**: `alias` is recommended for many fast selections; `cdf` uses binary search over the CDF.
|
|
73
108
|
|
|
74
|
-
|
|
109
|
+
## Advanced examples
|
|
75
110
|
|
|
76
|
-
|
|
111
|
+
### Custom RNG (deterministic for tests)
|
|
112
|
+
```ts
|
|
113
|
+
let i = 0
|
|
114
|
+
const values = [0.1, 0.8, 0.4]
|
|
115
|
+
const rng = () => values[i++ % values.length]
|
|
116
|
+
|
|
117
|
+
const result = pickMany([
|
|
118
|
+
{ id: 0, weight: 1, item: 'A' },
|
|
119
|
+
{ id: 1, weight: 1, item: 'B' },
|
|
120
|
+
], 2, { rng })
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
### Picker with `alias` method and weight updates
|
|
124
|
+
```ts
|
|
125
|
+
const picker = createWeightedPicker([
|
|
126
|
+
{ id: 0, weight: 1, item: 'A' },
|
|
127
|
+
{ id: 1, weight: 2, item: 'B' },
|
|
128
|
+
])
|
|
129
|
+
|
|
130
|
+
picker.pick()
|
|
131
|
+
picker.updateWeight(1, 5)
|
|
132
|
+
const batch = picker.pickMany(3)
|
|
77
133
|
```
|
|
78
|
-
MIT License
|
|
79
134
|
|
|
80
|
-
|
|
135
|
+
### Sampling without replacement
|
|
136
|
+
```ts
|
|
137
|
+
const res = pickMany([
|
|
138
|
+
{ id: 0, weight: 1, item: 'A' },
|
|
139
|
+
{ id: 1, weight: 1, item: 'B' },
|
|
140
|
+
{ id: 2, weight: 1, item: 'C' },
|
|
141
|
+
], 2, { replacement: false })
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
## Errors and validations
|
|
145
|
+
|
|
146
|
+
- List must be an array of objects.
|
|
147
|
+
- Each item must have `weight` (finite number ≥ 0) and `item`.
|
|
148
|
+
- If `normalize: false`, the sum of weights must be 1 (± `epsilon`).
|
|
149
|
+
- RNG must return a number `x` in the range [0, 1), and for some internal cases (without replacement) it requires 0 < x < 1.
|
|
150
|
+
|
|
151
|
+
## Size, types and compatibility
|
|
152
|
+
|
|
153
|
+
- TypeScript types included (`types` in the ESM distribution).
|
|
154
|
+
- ESM and CJS exports configured via `package.json` (`exports`, `import`/`require`).
|
|
155
|
+
|
|
156
|
+
## Development
|
|
157
|
+
|
|
158
|
+
Requirements: Node 16+
|
|
159
|
+
|
|
160
|
+
```bash
|
|
161
|
+
# install dependencies
|
|
162
|
+
npm install
|
|
163
|
+
|
|
164
|
+
# tests
|
|
165
|
+
npm test
|
|
166
|
+
|
|
167
|
+
# coverage
|
|
168
|
+
npm run coverage
|
|
169
|
+
|
|
170
|
+
# build (ESM and CJS)
|
|
171
|
+
npm run build
|
|
81
172
|
```
|
|
173
|
+
|
|
174
|
+
## Contributing
|
|
175
|
+
|
|
176
|
+
See `CONTRIBUTING.md` for guidelines. Please ensure tests and build pass before opening a PR.
|
|
177
|
+
|
|
178
|
+
## License
|
|
179
|
+
|
|
180
|
+
MIT © KossHackaton OneTeam
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.createWeightedPicker = exports.pickMany = exports.weightedPick = void 0;
|
|
37
|
+
const weightList_1 = __importStar(require("./weightList"));
|
|
38
|
+
exports.weightedPick = weightList_1.default;
|
|
39
|
+
Object.defineProperty(exports, "pickMany", { enumerable: true, get: function () { return weightList_1.pickMany; } });
|
|
40
|
+
Object.defineProperty(exports, "createWeightedPicker", { enumerable: true, get: function () { return weightList_1.createWeightedPicker; } });
|
|
41
|
+
exports.default = weightList_1.default;
|
|
42
|
+
module.exports = Object.assign(weightList_1.default, { weightedPick: weightList_1.default, pickMany: weightList_1.pickMany, createWeightedPicker: weightList_1.createWeightedPicker });
|
|
43
|
+
module.exports.default = weightList_1.default;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"type":"commonjs"}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.weightedPick = weightedPick;
|
|
4
|
+
exports.pickMany = pickMany;
|
|
5
|
+
exports.createWeightedPicker = createWeightedPicker;
|
|
6
|
+
const throwTypeError = (msg) => {
|
|
7
|
+
throw new TypeError(msg);
|
|
8
|
+
};
|
|
9
|
+
const defaultRNG = () => {
|
|
10
|
+
if (typeof globalThis !== 'undefined' && globalThis.crypto?.getRandomValues) {
|
|
11
|
+
const arr = new Uint32Array(1);
|
|
12
|
+
globalThis.crypto.getRandomValues(arr);
|
|
13
|
+
return arr[0] / 0x100000000;
|
|
14
|
+
}
|
|
15
|
+
return Math.random();
|
|
16
|
+
};
|
|
17
|
+
const validateOptions = (options) => {
|
|
18
|
+
if (!Array.isArray(options)) {
|
|
19
|
+
return throwTypeError('Weighted List expect Array of Objects as argument');
|
|
20
|
+
}
|
|
21
|
+
return options.map((opt, i) => {
|
|
22
|
+
if (!('weight' in opt))
|
|
23
|
+
throwTypeError('Every list item should have [weight] property');
|
|
24
|
+
if (!('item' in opt))
|
|
25
|
+
throwTypeError('Every list item should have [item] property');
|
|
26
|
+
const w = opt.weight;
|
|
27
|
+
if (typeof w !== 'number' || Number.isNaN(w) || !Number.isFinite(w) || w < 0) {
|
|
28
|
+
throwTypeError('Weights should be finite numbers >= 0');
|
|
29
|
+
}
|
|
30
|
+
return { id: opt.id ?? i, item: opt.item, weight: w };
|
|
31
|
+
});
|
|
32
|
+
};
|
|
33
|
+
const normalize = (weights, { normalize, epsilon }) => {
|
|
34
|
+
const total = weights.reduce((a, b) => a + b, 0);
|
|
35
|
+
if (normalize) {
|
|
36
|
+
if (total <= epsilon)
|
|
37
|
+
throwTypeError("Sum of 'weights' should be greater than 0");
|
|
38
|
+
return weights.map((w) => w / total);
|
|
39
|
+
}
|
|
40
|
+
if (Math.abs(total - 1) > epsilon)
|
|
41
|
+
throwTypeError("Sum of 'weights' should be equal 1");
|
|
42
|
+
return weights;
|
|
43
|
+
};
|
|
44
|
+
/** Pick a single item based on its weight */
|
|
45
|
+
function weightedPick(options, cfg = {}) {
|
|
46
|
+
const config = { normalize: true, epsilon: 1e-12, rng: defaultRNG, ...cfg };
|
|
47
|
+
const opts = validateOptions(options);
|
|
48
|
+
const weights = opts.map(o => o.weight);
|
|
49
|
+
const normalized = normalize(weights, config);
|
|
50
|
+
const num = config.rng();
|
|
51
|
+
if (typeof num !== 'number' || Number.isNaN(num) || num < 0 || num >= 1) {
|
|
52
|
+
throwTypeError('RNG should return a number x where 0 <= x < 1');
|
|
53
|
+
}
|
|
54
|
+
let acc = 0;
|
|
55
|
+
for (let i = 0; i < normalized.length; i++) {
|
|
56
|
+
acc += normalized[i];
|
|
57
|
+
if (num < acc) {
|
|
58
|
+
return { id: opts[i].id, item: opts[i].item };
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return { id: opts[opts.length - 1].id, item: opts[opts.length - 1].item };
|
|
62
|
+
}
|
|
63
|
+
/** Pick `k` items. When `replacement` is false sampling is without replacement */
|
|
64
|
+
function pickMany(options, k, cfg = {}) {
|
|
65
|
+
const { replacement = true, ...rest } = cfg;
|
|
66
|
+
if (replacement) {
|
|
67
|
+
return Array.from({ length: k }, () => weightedPick(options, rest));
|
|
68
|
+
}
|
|
69
|
+
const config = { normalize: true, epsilon: 1e-12, rng: defaultRNG, ...rest };
|
|
70
|
+
const opts = validateOptions(options);
|
|
71
|
+
const res = [];
|
|
72
|
+
opts.forEach((o) => {
|
|
73
|
+
const r = config.rng();
|
|
74
|
+
if (typeof r !== 'number' || Number.isNaN(r) || r <= 0 || r >= 1) {
|
|
75
|
+
throwTypeError('RNG should return a number x where 0 < x < 1');
|
|
76
|
+
}
|
|
77
|
+
if (o.weight > 0) {
|
|
78
|
+
const key = Math.pow(r, 1 / o.weight);
|
|
79
|
+
res.push({ key, option: o });
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
res.sort((a, b) => b.key - a.key);
|
|
83
|
+
return res.slice(0, k).map(r => ({ id: r.option.id, item: r.option.item }));
|
|
84
|
+
}
|
|
85
|
+
/** Create a weighted picker for many fast selections */
|
|
86
|
+
function createWeightedPicker(options, cfg = {}) {
|
|
87
|
+
const { method = 'alias', ...rest } = cfg;
|
|
88
|
+
const config = { normalize: true, epsilon: 1e-12, rng: defaultRNG, ...rest };
|
|
89
|
+
let opts = validateOptions(options);
|
|
90
|
+
let probs = [];
|
|
91
|
+
let alias = [];
|
|
92
|
+
let cdf = [];
|
|
93
|
+
const build = () => {
|
|
94
|
+
const weights = opts.map(o => o.weight);
|
|
95
|
+
const normalized = normalize(weights, config);
|
|
96
|
+
if (method === 'alias') {
|
|
97
|
+
const n = normalized.length;
|
|
98
|
+
const scaled = normalized.map(w => w * n);
|
|
99
|
+
const small = [];
|
|
100
|
+
const large = [];
|
|
101
|
+
probs = new Array(n).fill(0);
|
|
102
|
+
alias = new Array(n).fill(0);
|
|
103
|
+
scaled.forEach((w, i) => (w < 1 ? small : large).push(i));
|
|
104
|
+
while (small.length && large.length) {
|
|
105
|
+
const l = small.pop();
|
|
106
|
+
const g = large.pop();
|
|
107
|
+
probs[l] = scaled[l];
|
|
108
|
+
alias[l] = g;
|
|
109
|
+
scaled[g] = scaled[g] + scaled[l] - 1;
|
|
110
|
+
if (scaled[g] < 1)
|
|
111
|
+
small.push(g);
|
|
112
|
+
else
|
|
113
|
+
large.push(g);
|
|
114
|
+
}
|
|
115
|
+
;
|
|
116
|
+
[...large, ...small].forEach(i => (probs[i] = 1));
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
cdf = [];
|
|
120
|
+
let sum = 0;
|
|
121
|
+
normalized.forEach((w) => {
|
|
122
|
+
sum += w;
|
|
123
|
+
cdf.push(sum);
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
build();
|
|
128
|
+
const pick = () => {
|
|
129
|
+
if (method === 'alias') {
|
|
130
|
+
const n = opts.length;
|
|
131
|
+
const i = Math.floor(config.rng() * n);
|
|
132
|
+
const r = config.rng();
|
|
133
|
+
const idx = r < probs[i] ? i : alias[i];
|
|
134
|
+
return { id: opts[idx].id, item: opts[idx].item };
|
|
135
|
+
}
|
|
136
|
+
const r = config.rng();
|
|
137
|
+
if (typeof r !== 'number' || Number.isNaN(r) || r < 0 || r >= 1) {
|
|
138
|
+
throwTypeError('RNG should return a number x where 0 <= x < 1');
|
|
139
|
+
}
|
|
140
|
+
let low = 0;
|
|
141
|
+
let high = cdf.length - 1;
|
|
142
|
+
while (low < high) {
|
|
143
|
+
const mid = Math.floor((low + high) / 2);
|
|
144
|
+
if (r < cdf[mid])
|
|
145
|
+
high = mid;
|
|
146
|
+
else
|
|
147
|
+
low = mid + 1;
|
|
148
|
+
}
|
|
149
|
+
return { id: opts[low].id, item: opts[low].item };
|
|
150
|
+
};
|
|
151
|
+
return {
|
|
152
|
+
pick,
|
|
153
|
+
pickMany: (k) => Array.from({ length: k }, () => pick()),
|
|
154
|
+
updateWeight: (id, weight) => {
|
|
155
|
+
const idx = opts.findIndex(o => o.id === id);
|
|
156
|
+
if (idx === -1)
|
|
157
|
+
throwTypeError('ID not found');
|
|
158
|
+
if (typeof weight !== 'number' || Number.isNaN(weight) || !Number.isFinite(weight) || weight < 0) {
|
|
159
|
+
throwTypeError('Weights should be finite numbers >= 0');
|
|
160
|
+
}
|
|
161
|
+
opts[idx].weight = weight;
|
|
162
|
+
build();
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
exports.default = weightedPick;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import weightedPick, { pickMany, createWeightedPicker, RNG, PickConfig, Method, WeightedInput, WeightedResult } from './weightList';
|
|
2
|
+
export type { RNG, PickConfig, Method, WeightedInput, WeightedResult };
|
|
3
|
+
export { weightedPick, pickMany, createWeightedPicker };
|
|
4
|
+
export default weightedPick;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import weightedPick, { pickMany, createWeightedPicker, } from './weightList';
|
|
2
|
+
export { weightedPick, pickMany, createWeightedPicker };
|
|
3
|
+
export default weightedPick;
|
|
4
|
+
module.exports = Object.assign(weightedPick, { weightedPick, pickMany, createWeightedPicker });
|
|
5
|
+
module.exports.default = weightedPick;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** RNG function returning a float x where 0 <= x < 1 */
|
|
2
|
+
export type RNG = () => number;
|
|
3
|
+
/** Configuration shared by all pickers */
|
|
4
|
+
export interface PickConfig {
|
|
5
|
+
/** Normalize weights so that they sum 1. Defaults to `true` */
|
|
6
|
+
normalize?: boolean;
|
|
7
|
+
/** Tolerance when checking weight sums. Defaults to `1e-12` */
|
|
8
|
+
epsilon?: number;
|
|
9
|
+
/** Random number generator. Defaults to crypto or `Math.random` */
|
|
10
|
+
rng?: RNG;
|
|
11
|
+
}
|
|
12
|
+
export interface WeightedInput<T> {
|
|
13
|
+
id?: number;
|
|
14
|
+
weight: number;
|
|
15
|
+
item: T;
|
|
16
|
+
}
|
|
17
|
+
export interface WeightedResult<T> {
|
|
18
|
+
id: number;
|
|
19
|
+
item: T;
|
|
20
|
+
}
|
|
21
|
+
/** Pick a single item based on its weight */
|
|
22
|
+
export declare function weightedPick<T>(options: ReadonlyArray<WeightedInput<T>>, cfg?: PickConfig): WeightedResult<T>;
|
|
23
|
+
/** Pick `k` items. When `replacement` is false sampling is without replacement */
|
|
24
|
+
export declare function pickMany<T>(options: ReadonlyArray<WeightedInput<T>>, k: number, cfg?: PickConfig & {
|
|
25
|
+
replacement?: boolean;
|
|
26
|
+
}): Array<WeightedResult<T>>;
|
|
27
|
+
export type Method = 'cdf' | 'alias';
|
|
28
|
+
/** Create a weighted picker for many fast selections */
|
|
29
|
+
export declare function createWeightedPicker<T>(options: ReadonlyArray<WeightedInput<T>>, cfg?: PickConfig & {
|
|
30
|
+
method?: Method;
|
|
31
|
+
}): {
|
|
32
|
+
pick: () => WeightedResult<T>;
|
|
33
|
+
pickMany: (k: number) => WeightedResult<T>[];
|
|
34
|
+
updateWeight: (id: number, weight: number) => void;
|
|
35
|
+
};
|
|
36
|
+
export default weightedPick;
|