random-weighted-pick 2.0.1 → 2.1.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/LICENSE +1 -1
- package/README.md +209 -116
- package/dist/cjs/index.d.ts +18 -0
- package/dist/cjs/index.js +3 -45
- package/dist/cjs/weightList.d.ts +42 -0
- package/dist/cjs/weightList.js +200 -138
- package/dist/esm/index.d.ts +2 -4
- package/dist/esm/index.js +1 -7
- package/dist/esm/weightList.d.ts +24 -18
- package/dist/esm/weightList.js +200 -138
- package/package.json +35 -22
- package/.babelrc +0 -6
- package/.circleci/config.yml +0 -20
- package/.eslintrc.json +0 -7
- package/.local-tests/esm-smoke/package-lock.json +0 -25
- package/.local-tests/esm-smoke/package.json +0 -16
- package/.local-tests/esm-smoke/test.mjs +0 -52
- package/.local-tests/npm-smoke/package-lock.json +0 -25
- package/.local-tests/npm-smoke/package.json +0 -15
- package/.local-tests/npm-smoke/test.js +0 -61
- package/.prettierrc +0 -4
- package/CONTRIBUTING.md +0 -9
- package/jest.config.cjs +0 -5
- package/random-weighted-pick-2.0.0.tgz +0 -0
- package/random-weighted-pick-2.0.1.tgz +0 -0
- package/tsconfig.cjs.json +0 -8
- package/tsconfig.esm.json +0 -9
- package/tsconfig.json +0 -20
package/LICENSE
CHANGED
package/README.md
CHANGED
|
@@ -1,180 +1,273 @@
|
|
|
1
1
|
# random-weighted-pick
|
|
2
2
|
|
|
3
|
-
[
|
|
8
|
-

|
|
9
|
-

|
|
10
|
-
[](./LICENSE)
|
|
3
|
+
[](https://www.npmjs.com/package/random-weighted-pick)
|
|
4
|
+
[](https://github.com/phellipeandrade/random-weighted-pick/actions/workflows/ci.yml)
|
|
5
|
+
[](https://www.npmjs.com/package/random-weighted-pick)
|
|
6
|
+
[](./LICENSE)
|
|
11
7
|
|
|
12
|
-
|
|
8
|
+
**Weighted random selection for JavaScript and TypeScript, with zero runtime dependencies.**
|
|
9
|
+
|
|
10
|
+
Give each item a relative weight and select it with probability proportional to that weight. Use one-off selection for small lists, sample multiple items with or without replacement, or prepare a reusable picker for high-throughput applications.
|
|
11
|
+
|
|
12
|
+
- Relative weights, probabilities, and percentages.
|
|
13
|
+
- Generic TypeScript types, ESM, and CommonJS.
|
|
14
|
+
- O(1) draws with the alias method, or O(log n) with binary search over a cumulative distribution.
|
|
15
|
+
- Injectable random number generator (RNG) for reproducible simulations and tests.
|
|
16
|
+
- Atomic weight updates for long-lived pickers.
|
|
13
17
|
|
|
14
18
|
## Installation
|
|
15
19
|
|
|
16
|
-
```
|
|
20
|
+
```sh
|
|
17
21
|
npm install random-weighted-pick
|
|
18
22
|
```
|
|
19
23
|
|
|
20
|
-
-
|
|
21
|
-
- Supports **ESM** and **CommonJS**.
|
|
22
|
-
|
|
23
|
-
## Import
|
|
24
|
-
|
|
25
|
-
```ts
|
|
26
|
-
// ESM
|
|
27
|
-
import weightedPick, { pickMany, createWeightedPicker } from 'random-weighted-pick'
|
|
28
|
-
|
|
29
|
-
// CommonJS
|
|
30
|
-
// const { weightedPick, pickMany, createWeightedPicker } = require('random-weighted-pick')
|
|
31
|
-
// or: const weightedPick = require('random-weighted-pick')
|
|
32
|
-
```
|
|
24
|
+
Runtime: Node.js 16+ and modern browsers through an ESM-compatible bundler. Development and CI use Node.js 22 or newer.
|
|
33
25
|
|
|
34
26
|
## Quick start
|
|
35
27
|
|
|
36
28
|
```ts
|
|
29
|
+
import weightedPick from 'random-weighted-pick'
|
|
30
|
+
|
|
37
31
|
const options = [
|
|
38
|
-
{
|
|
39
|
-
{
|
|
40
|
-
{
|
|
41
|
-
{ id: 3, weight: 0.1, item: 3 },
|
|
32
|
+
{ weight: 70, item: 'standard' },
|
|
33
|
+
{ weight: 25, item: 'premium' },
|
|
34
|
+
{ weight: 5, item: 'special' },
|
|
42
35
|
]
|
|
43
36
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
37
|
+
const { id, item } = weightedPick(options)
|
|
38
|
+
console.log(id, item)
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
The first option has a 70% chance, the second 25%, and the third 5%. Weights `[70, 25, 5]`, `[0.7, 0.25, 0.05]`, and `[14, 5, 1]` represent the same distribution.
|
|
47
42
|
|
|
48
|
-
|
|
49
|
-
|
|
43
|
+
| Option | Weight | Probability |
|
|
44
|
+
| --- | ---: | ---: |
|
|
45
|
+
| standard | 70 | 70% |
|
|
46
|
+
| premium | 25 | 25% |
|
|
47
|
+
| special | 5 | 5% |
|
|
50
48
|
|
|
51
|
-
|
|
52
|
-
const noReplacement = pickMany(options, 2, { replacement: false })
|
|
49
|
+
The result contains the original item and its numeric ID. When an ID is omitted, it defaults to the zero-based array index.
|
|
53
50
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
51
|
+
### CommonJS
|
|
52
|
+
|
|
53
|
+
```js
|
|
54
|
+
const weightedPick = require('random-weighted-pick')
|
|
55
|
+
const { pickMany, createWeightedPicker } = weightedPick
|
|
57
56
|
```
|
|
58
57
|
|
|
59
|
-
|
|
58
|
+
Named imports and the default import are also supported in ESM.
|
|
60
59
|
|
|
61
|
-
|
|
62
|
-
Pick 1 item according to its weight.
|
|
60
|
+
## API reference
|
|
63
61
|
|
|
64
|
-
### `
|
|
65
|
-
Pick `k` items. When `replacement: false`, sampling is without replacement.
|
|
62
|
+
### `weightedPick(options, config?)`
|
|
66
63
|
|
|
67
|
-
|
|
68
|
-
|
|
64
|
+
Select one item. Returns `{ id: number, item: T }`.
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
import { weightedPick } from 'random-weighted-pick'
|
|
68
|
+
|
|
69
|
+
const selected = weightedPick([
|
|
70
|
+
{ id: 101, weight: 3, item: { name: 'A' } },
|
|
71
|
+
{ id: 102, weight: 1, item: { name: 'B' } },
|
|
72
|
+
])
|
|
73
|
+
// selected.item.name is typed as string
|
|
74
|
+
```
|
|
69
75
|
|
|
70
|
-
|
|
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.
|
|
76
|
+
### `pickMany(options, k, config?)`
|
|
74
77
|
|
|
75
|
-
|
|
78
|
+
Return up to `k` results. With replacement (the default), an entry may appear multiple times and exactly `k` draws are made. Without replacement, each entry can appear at most once, and the result is capped at the number of positive-weight entries.
|
|
76
79
|
|
|
77
80
|
```ts
|
|
78
|
-
|
|
79
|
-
id?: number
|
|
80
|
-
weight: number
|
|
81
|
-
item: T
|
|
82
|
-
}
|
|
81
|
+
import { pickMany } from 'random-weighted-pick'
|
|
83
82
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
item:
|
|
87
|
-
}
|
|
83
|
+
const candidates = [
|
|
84
|
+
{ weight: 5, item: 'A' },
|
|
85
|
+
{ weight: 3, item: 'B' },
|
|
86
|
+
{ weight: 2, item: 'C' },
|
|
87
|
+
]
|
|
88
88
|
|
|
89
|
-
|
|
89
|
+
const independent = pickMany(candidates, 10)
|
|
90
|
+
const distinct = pickMany(candidates, 2, { replacement: false })
|
|
91
|
+
```
|
|
90
92
|
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
rng?: RNG // default: crypto.getRandomValues (when available) or Math.random
|
|
95
|
-
}
|
|
93
|
+
Sampling without replacement produces a weighted random ordering: after each selected entry is removed, the remaining entries are selected proportionally to their remaining weights. Distinctness applies to entries, so duplicate IDs or equal item values may still occur. A count of zero returns an empty array after validating the options, without consuming random values.
|
|
94
|
+
|
|
95
|
+
### `createWeightedPicker(options, config?)`
|
|
96
96
|
|
|
97
|
-
|
|
97
|
+
Precompute a distribution and reuse it for repeated draws.
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
import { createWeightedPicker } from 'random-weighted-pick'
|
|
101
|
+
|
|
102
|
+
const picker = createWeightedPicker([
|
|
103
|
+
{ id: 1, weight: 9, item: 'primary' },
|
|
104
|
+
{ id: 2, weight: 1, item: 'canary' },
|
|
105
|
+
])
|
|
106
|
+
|
|
107
|
+
const next = picker.pick()
|
|
108
|
+
const batch = picker.pickMany(100)
|
|
109
|
+
|
|
110
|
+
picker.updateWeight(2, 3) // change one weight
|
|
111
|
+
picker.updateWeights([
|
|
112
|
+
{ id: 1, weight: 4 },
|
|
113
|
+
{ id: 2, weight: 6 },
|
|
114
|
+
]) // apply both changes in one rebuild
|
|
98
115
|
```
|
|
99
116
|
|
|
100
|
-
|
|
101
|
-
|
|
117
|
+
| Method | Description |
|
|
118
|
+
| --- | --- |
|
|
119
|
+
| `pick()` | Select one item. |
|
|
120
|
+
| `pickMany(k)` | Select exactly `k` items with replacement. |
|
|
121
|
+
| `updateWeight(id, weight)` | Change one weight and rebuild. |
|
|
122
|
+
| `updateWeights(updates)` | Apply multiple changes atomically, with one rebuild. |
|
|
123
|
+
|
|
124
|
+
A failed update leaves the previous distribution usable. Input arrays and their option objects are not modified. Item values are returned by reference. If IDs repeat, updates address the first matching entry. Prefer unique IDs when using updates.
|
|
102
125
|
|
|
103
|
-
##
|
|
126
|
+
## Configuration
|
|
104
127
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
128
|
+
| Option | Default | Applies to | Description |
|
|
129
|
+
| --- | --- | --- | --- |
|
|
130
|
+
| `normalize` | `true` | All | Accept relative weights. With `false`, require a sum within epsilon of 1. |
|
|
131
|
+
| `epsilon` | `1e-12` | All | Finite, non-negative absolute tolerance for strict mode. |
|
|
132
|
+
| `rng` | Built-in RNG | All | Function returning a finite number in `[0, 1)`. |
|
|
133
|
+
| `replacement` | `true` | `pickMany` | Allow repeated selection of the same entry. |
|
|
134
|
+
| `method` | `'alias'` | `createWeightedPicker` | Choose `'alias'` or `'cdf'`. |
|
|
108
135
|
|
|
109
|
-
|
|
136
|
+
Strict mode validates the sum before using the actual total for proportional sampling, avoiding gaps caused by floating-point rounding.
|
|
110
137
|
|
|
111
|
-
### Custom RNG (deterministic for tests)
|
|
112
138
|
```ts
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
const result = pickMany([
|
|
118
|
-
{ id: 0, weight: 1, item: 'A' },
|
|
119
|
-
{ id: 1, weight: 1, item: 'B' },
|
|
120
|
-
], 2, { rng })
|
|
139
|
+
const pick = weightedPick(
|
|
140
|
+
[{ weight: 0.3, item: 'A' }, { weight: 0.7, item: 'B' }],
|
|
141
|
+
{ normalize: false },
|
|
142
|
+
)
|
|
121
143
|
```
|
|
122
144
|
|
|
123
|
-
|
|
145
|
+
The built-in RNG uses 53-bit uniform samples from Web Crypto when available and falls back to `Math.random`. You can supply `Math.random` explicitly for simulation throughput or a seeded RNG for reproducible results. Alias draws consume two RNG values, CDF and single draws consume one, and sampling without replacement consumes one per positive-weight entry. An RNG value of zero is valid everywhere.
|
|
146
|
+
|
|
147
|
+
## Practical examples
|
|
148
|
+
|
|
149
|
+
### Weighted routing and canary releases
|
|
150
|
+
|
|
124
151
|
```ts
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
152
|
+
import { createWeightedPicker } from 'random-weighted-pick'
|
|
153
|
+
|
|
154
|
+
const upstream = createWeightedPicker([
|
|
155
|
+
{ id: 1, weight: 95, item: 'https://stable.example.com' },
|
|
156
|
+
{ id: 2, weight: 5, item: 'https://canary.example.com' },
|
|
128
157
|
])
|
|
129
158
|
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
159
|
+
const url = upstream.pick().item
|
|
160
|
+
|
|
161
|
+
// Increase traffic to the canary without recreating the picker.
|
|
162
|
+
upstream.updateWeights([
|
|
163
|
+
{ id: 1, weight: 80 },
|
|
164
|
+
{ id: 2, weight: 20 },
|
|
165
|
+
])
|
|
133
166
|
```
|
|
134
167
|
|
|
135
|
-
|
|
168
|
+
Each request is independently randomized. For sticky A/B cohorts or consistent routing, use a stable user-ID hash or another persistent assignment mechanism.
|
|
169
|
+
|
|
170
|
+
### Weighted simulations
|
|
171
|
+
|
|
136
172
|
```ts
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
173
|
+
import { pickMany } from 'random-weighted-pick'
|
|
174
|
+
|
|
175
|
+
let state = 42
|
|
176
|
+
const rng = () => {
|
|
177
|
+
state = (Math.imul(state, 1664525) + 1013904223) >>> 0
|
|
178
|
+
return state / 2 ** 32
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const samples = pickMany([
|
|
182
|
+
{ weight: 60, item: 'sunny' },
|
|
183
|
+
{ weight: 30, item: 'cloudy' },
|
|
184
|
+
{ weight: 10, item: 'rainy' },
|
|
185
|
+
], 1000, { rng })
|
|
142
186
|
```
|
|
143
187
|
|
|
144
|
-
|
|
188
|
+
The example RNG is deterministic and suitable for simulations and tests. It is not cryptographically secure.
|
|
145
189
|
|
|
146
|
-
|
|
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.
|
|
190
|
+
## Performance and algorithms
|
|
150
191
|
|
|
151
|
-
|
|
192
|
+
Let `n` be the number of options and `k` the number of requested draws.
|
|
152
193
|
|
|
153
|
-
|
|
154
|
-
|
|
194
|
+
| Operation | Time | Extra space |
|
|
195
|
+
| --- | --- | --- |
|
|
196
|
+
| `weightedPick` | O(n) | O(n) |
|
|
197
|
+
| `pickMany` with replacement | O(n + k log n) | O(n + k) |
|
|
198
|
+
| `pickMany` without replacement | O(n log n) | O(n) |
|
|
199
|
+
| Build a CDF picker | O(n) | O(n) |
|
|
200
|
+
| CDF draw | O(log n) | O(1) |
|
|
201
|
+
| Build an alias picker | O(n) | O(n) |
|
|
202
|
+
| Alias draw | O(1) | O(1) |
|
|
203
|
+
| Update `m` weights | O(n + m) | O(n) |
|
|
155
204
|
|
|
156
|
-
|
|
205
|
+
Single draws scan the cumulative distribution. Repeated draws reuse a precomputed CDF (binary search) or Walker/Vose alias tables. Sampling without replacement ranks independent exponential waiting times in log space, equivalent to weighted random keys, to avoid the numerical problems of raising small or large weights to powers.
|
|
157
206
|
|
|
158
|
-
|
|
207
|
+
Before summation, relative weights are scaled by their largest weight to avoid overflow when the raw total exceeds `Number.MAX_VALUE`. Zero-weight entries cannot be selected. As with other floating-point implementations, extremely small probability ratios may be below representable precision or RNG resolution.
|
|
159
208
|
|
|
160
|
-
|
|
161
|
-
# install dependencies
|
|
162
|
-
npm install
|
|
209
|
+
Run a local benchmark with:
|
|
163
210
|
|
|
164
|
-
|
|
165
|
-
npm
|
|
211
|
+
```sh
|
|
212
|
+
npm run benchmark
|
|
213
|
+
```
|
|
166
214
|
|
|
167
|
-
|
|
168
|
-
npm run coverage
|
|
215
|
+
The benchmark compares the one-off API, reusable CDF and alias pickers, and batch sampling for 10, 100, and 1,000 entries. It uses `Math.random` and reports draws per second on your own machine.
|
|
169
216
|
|
|
170
|
-
|
|
171
|
-
|
|
217
|
+
## Validation
|
|
218
|
+
|
|
219
|
+
Invalid inputs throw an error:
|
|
220
|
+
|
|
221
|
+
- Empty arrays, missing `item` or `weight`, non-object entries, or non-finite IDs.
|
|
222
|
+
- Negative, non-numeric, non-finite, or all-zero weights.
|
|
223
|
+
- Strict-mode sums outside the configured tolerance.
|
|
224
|
+
- Invalid configuration, unsupported picker methods, unknown update IDs, or RNG values outside `[0, 1)`.
|
|
225
|
+
- Counts that are negative, fractional, non-numeric, or beyond the JavaScript array length limit (throws `RangeError`).
|
|
226
|
+
|
|
227
|
+
Use a positive weight to make an entry eligible. An omitted ID uses the array index. All other validation errors throw `TypeError`.
|
|
228
|
+
|
|
229
|
+
## TypeScript
|
|
230
|
+
|
|
231
|
+
```ts
|
|
232
|
+
import type {
|
|
233
|
+
RNG,
|
|
234
|
+
PickConfig,
|
|
235
|
+
SampleConfig,
|
|
236
|
+
PickerConfig,
|
|
237
|
+
Method,
|
|
238
|
+
WeightedInput,
|
|
239
|
+
WeightedResult,
|
|
240
|
+
WeightedPicker,
|
|
241
|
+
} from 'random-weighted-pick'
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
Generic item types are inferred from the input. Type declarations are included for both ESM and CommonJS.
|
|
245
|
+
|
|
246
|
+
## Development
|
|
247
|
+
|
|
248
|
+
```sh
|
|
249
|
+
npm ci
|
|
250
|
+
npm run typecheck
|
|
251
|
+
npm test
|
|
252
|
+
npm run coverage
|
|
253
|
+
npm run benchmark
|
|
254
|
+
npm pack --dry-run
|
|
172
255
|
```
|
|
173
256
|
|
|
174
|
-
|
|
257
|
+
Tests cover deterministic boundaries, invalid inputs, distribution accuracy, numeric extremes, atomic updates, runtime imports, and TypeScript consumer types. See [CONTRIBUTING.md](./CONTRIBUTING.md).
|
|
258
|
+
|
|
259
|
+
## Migration from 2.0
|
|
260
|
+
|
|
261
|
+
Existing default and named imports, selection functions, picker methods, and Node.js runtime support are retained. Version 2.1 adds `updateWeights`, exports additional types, and corrects edge cases:
|
|
262
|
+
|
|
263
|
+
- All-zero and empty distributions now fail consistently.
|
|
264
|
+
- Tiny positive totals and overflowing raw totals are supported in relative mode.
|
|
265
|
+
- Sampling without replacement accepts RNG zero, skips zero-weight entries, and validates strict mode.
|
|
266
|
+
- Invalid counts are rejected rather than silently truncated or coerced.
|
|
267
|
+
- Failed updates preserve the previous distribution.
|
|
175
268
|
|
|
176
|
-
|
|
269
|
+
A seeded RNG may produce a different sequence from 2.0 due to numerical fixes and the exclusion of zero-weight entries from alias tables.
|
|
177
270
|
|
|
178
271
|
## License
|
|
179
272
|
|
|
180
|
-
MIT
|
|
273
|
+
[MIT](./LICENSE)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type * as core from './weightList.js'
|
|
2
|
+
declare const api: typeof core.weightedPick & {
|
|
3
|
+
default: typeof core.weightedPick
|
|
4
|
+
weightedPick: typeof core.weightedPick
|
|
5
|
+
pickMany: typeof core.pickMany
|
|
6
|
+
createWeightedPicker: typeof core.createWeightedPicker
|
|
7
|
+
}
|
|
8
|
+
declare namespace api {
|
|
9
|
+
export type RNG = core.RNG
|
|
10
|
+
export type PickConfig = core.PickConfig
|
|
11
|
+
export type SampleConfig = core.SampleConfig
|
|
12
|
+
export type PickerConfig = core.PickerConfig
|
|
13
|
+
export type Method = core.Method
|
|
14
|
+
export type WeightedInput<T> = core.WeightedInput<T>
|
|
15
|
+
export type WeightedResult<T> = core.WeightedResult<T>
|
|
16
|
+
export type WeightedPicker<T> = core.WeightedPicker<T>
|
|
17
|
+
}
|
|
18
|
+
export = api
|
package/dist/cjs/index.js
CHANGED
|
@@ -1,45 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
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_js_1 = __importStar(require("./weightList.js"));
|
|
38
|
-
exports.weightedPick = weightList_js_1.default;
|
|
39
|
-
Object.defineProperty(exports, "pickMany", { enumerable: true, get: function () { return weightList_js_1.pickMany; } });
|
|
40
|
-
Object.defineProperty(exports, "createWeightedPicker", { enumerable: true, get: function () { return weightList_js_1.createWeightedPicker; } });
|
|
41
|
-
exports.default = weightList_js_1.default;
|
|
42
|
-
if (typeof module !== 'undefined' && module?.exports) {
|
|
43
|
-
module.exports = Object.assign(weightList_js_1.default, { weightedPick: weightList_js_1.default, pickMany: weightList_js_1.pickMany, createWeightedPicker: weightList_js_1.createWeightedPicker });
|
|
44
|
-
module.exports.default = weightList_js_1.default;
|
|
45
|
-
}
|
|
1
|
+
'use strict'
|
|
2
|
+
const { weightedPick, pickMany, createWeightedPicker } = require('./weightList.js')
|
|
3
|
+
module.exports = Object.assign(weightedPick, { default: weightedPick, weightedPick, pickMany, createWeightedPicker })
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/** Uniform random number in [0, 1). */
|
|
2
|
+
export type RNG = () => number;
|
|
3
|
+
export interface PickConfig {
|
|
4
|
+
/** Accept relative weights. Defaults to true. */
|
|
5
|
+
normalize?: boolean;
|
|
6
|
+
/** Absolute tolerance for a sum of 1 in strict mode. Defaults to 1e-12. */
|
|
7
|
+
epsilon?: number;
|
|
8
|
+
rng?: RNG;
|
|
9
|
+
}
|
|
10
|
+
export interface WeightedInput<T> {
|
|
11
|
+
id?: number;
|
|
12
|
+
weight: number;
|
|
13
|
+
item: T;
|
|
14
|
+
}
|
|
15
|
+
export interface WeightedResult<T> {
|
|
16
|
+
id: number;
|
|
17
|
+
item: T;
|
|
18
|
+
}
|
|
19
|
+
export type Method = 'cdf' | 'alias';
|
|
20
|
+
export interface SampleConfig extends PickConfig {
|
|
21
|
+
replacement?: boolean;
|
|
22
|
+
}
|
|
23
|
+
export interface PickerConfig extends PickConfig {
|
|
24
|
+
method?: Method;
|
|
25
|
+
}
|
|
26
|
+
export interface WeightedPicker<T> {
|
|
27
|
+
pick(): WeightedResult<T>;
|
|
28
|
+
pickMany(k: number): WeightedResult<T>[];
|
|
29
|
+
updateWeight(id: number, weight: number): void;
|
|
30
|
+
/** Apply multiple changes atomically, rebuilding the tables only once. */
|
|
31
|
+
updateWeights(updates: ReadonlyArray<{
|
|
32
|
+
id: number;
|
|
33
|
+
weight: number;
|
|
34
|
+
}>): void;
|
|
35
|
+
}
|
|
36
|
+
/** Select one entry with probability proportional to its weight. */
|
|
37
|
+
export declare function weightedPick<T>(options: ReadonlyArray<WeightedInput<T>>, cfg?: PickConfig): WeightedResult<T>;
|
|
38
|
+
/** Sample with replacement by default; otherwise return up to k distinct entries. */
|
|
39
|
+
export declare function pickMany<T>(options: ReadonlyArray<WeightedInput<T>>, k: number, cfg?: SampleConfig): WeightedResult<T>[];
|
|
40
|
+
/** Prepare reusable lookup tables for repeated selections. */
|
|
41
|
+
export declare function createWeightedPicker<T>(options: ReadonlyArray<WeightedInput<T>>, cfg?: PickerConfig): WeightedPicker<T>;
|
|
42
|
+
export default weightedPick;
|