random-weighted-pick 2.0.0 → 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.
@@ -3,164 +3,226 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.weightedPick = weightedPick;
4
4
  exports.pickMany = pickMany;
5
5
  exports.createWeightedPicker = createWeightedPicker;
6
- const throwTypeError = (msg) => {
7
- throw new TypeError(msg);
8
- };
6
+ const randomWords = new Uint32Array(2);
9
7
  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;
8
+ if (typeof globalThis.crypto?.getRandomValues === 'function') {
9
+ globalThis.crypto.getRandomValues(randomWords);
10
+ return ((randomWords[0] >>> 11) * 0x100000000 + randomWords[1]) / 0x20000000000000;
14
11
  }
15
12
  return Math.random();
16
13
  };
17
- const validateOptions = (options) => {
14
+ function resolveConfig(cfg) {
15
+ const { normalize = true, epsilon = 1e-12, rng = defaultRNG } = cfg;
16
+ if (typeof normalize !== 'boolean')
17
+ throw new TypeError('normalize must be a boolean');
18
+ if (!Number.isFinite(epsilon) || epsilon < 0) {
19
+ throw new TypeError('epsilon must be a finite non-negative number');
20
+ }
21
+ if (typeof rng !== 'function')
22
+ throw new TypeError('rng must be a function');
23
+ return { normalize, epsilon, rng };
24
+ }
25
+ function random(rng) {
26
+ const value = rng();
27
+ if (!Number.isFinite(value) || value < 0 || value >= 1) {
28
+ throw new TypeError('RNG should return a number x where 0 <= x < 1');
29
+ }
30
+ return value;
31
+ }
32
+ function validateWeight(weight) {
33
+ if (!Number.isFinite(weight) || weight < 0) {
34
+ throw new TypeError('Weights should be finite numbers >= 0');
35
+ }
36
+ }
37
+ function validateCount(k) {
38
+ if (!Number.isSafeInteger(k) || k < 0 || k > 0xffffffff) {
39
+ throw new RangeError('k must be a non-negative integer within the array length limit');
40
+ }
41
+ }
42
+ function validateOptions(options) {
18
43
  if (!Array.isArray(options)) {
19
- return throwTypeError('Weighted List expect Array of Objects as argument');
44
+ throw new TypeError('Weighted List expect Array of Objects as argument');
20
45
  }
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');
46
+ return Array.from(options, (option, index) => {
47
+ if (option === null || typeof option !== 'object') {
48
+ throw new TypeError('Every list item should be an object');
29
49
  }
30
- return { id: opt.id ?? i, item: opt.item, weight: w };
50
+ if (!('weight' in option))
51
+ throw new TypeError('Every list item should have [weight] property');
52
+ if (!('item' in option))
53
+ throw new TypeError('Every list item should have [item] property');
54
+ const weight = option.weight;
55
+ validateWeight(weight);
56
+ const id = option.id ?? index;
57
+ if (!Number.isFinite(id))
58
+ throw new TypeError('ID must be a finite number');
59
+ return { id, item: option.item, weight };
31
60
  });
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);
61
+ }
62
+ function validateTotal(entries, config) {
63
+ let max = 0;
64
+ let total = 0;
65
+ for (const entry of entries) {
66
+ max = Math.max(max, entry.weight);
67
+ if (!config.normalize)
68
+ total += entry.weight;
39
69
  }
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');
70
+ if (max === 0)
71
+ throw new TypeError("Sum of 'weights' should be greater than 0");
72
+ if (!config.normalize && (!Number.isFinite(total) || Math.abs(total - 1) > config.epsilon)) {
73
+ throw new TypeError("Sum of 'weights' should be equal 1");
53
74
  }
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
- }
75
+ return max;
76
+ }
77
+ function result(entry) {
78
+ return { id: entry.id, item: entry.item };
79
+ }
80
+ /** Scale before summing to avoid overflow and retain small absolute weights. */
81
+ function distribution(entries, config) {
82
+ const max = validateTotal(entries, config);
83
+ const active = [];
84
+ const cumulative = [];
85
+ const scaled = [];
86
+ let total = 0;
87
+ for (const entry of entries) {
88
+ const weight = entry.weight / max;
89
+ if (weight === 0)
90
+ continue;
91
+ total += weight;
92
+ active.push(entry);
93
+ scaled.push(weight);
94
+ cumulative.push(total);
95
+ }
96
+ return { active, cumulative, scaled, total };
97
+ }
98
+ function buildDraw(entries, config, method) {
99
+ const { active, cumulative, scaled, total } = distribution(entries, config);
100
+ if (method === 'cdf') {
101
+ return () => {
102
+ const target = random(config.rng) * total;
103
+ let low = 0;
104
+ let high = cumulative.length - 1;
105
+ while (low < high) {
106
+ const mid = low + Math.floor((high - low) / 2);
107
+ if (target < cumulative[mid])
108
+ high = mid;
109
+ else
110
+ low = mid + 1;
111
+ }
112
+ return result(active[low]);
113
+ };
60
114
  }
61
- return { id: opts[opts.length - 1].id, item: opts[opts.length - 1].item };
115
+ const n = active.length;
116
+ const probabilities = new Float64Array(n);
117
+ const aliases = new Uint32Array(n);
118
+ const small = [];
119
+ const large = [];
120
+ for (let i = 0; i < n; i++) {
121
+ scaled[i] = (scaled[i] / total) * n;
122
+ (scaled[i] < 1 ? small : large).push(i);
123
+ }
124
+ while (small.length && large.length) {
125
+ const l = small.pop();
126
+ const g = large.pop();
127
+ probabilities[l] = scaled[l];
128
+ aliases[l] = g;
129
+ scaled[g] = (scaled[g] + scaled[l]) - 1;
130
+ (scaled[g] < 1 ? small : large).push(g);
131
+ }
132
+ for (const index of small)
133
+ probabilities[index] = 1;
134
+ for (const index of large)
135
+ probabilities[index] = 1;
136
+ return () => {
137
+ const index = Math.min(Math.floor(random(config.rng) * n), n - 1);
138
+ const coin = random(config.rng);
139
+ return result(active[coin < probabilities[index] ? index : aliases[index]]);
140
+ };
141
+ }
142
+ /** Select one entry with probability proportional to its weight. */
143
+ function weightedPick(options, cfg = {}) {
144
+ const config = resolveConfig(cfg);
145
+ const entries = validateOptions(options);
146
+ const max = validateTotal(entries, config);
147
+ let total = 0;
148
+ for (const entry of entries)
149
+ total += entry.weight / max;
150
+ const target = random(config.rng) * total;
151
+ let cumulative = 0;
152
+ let last = entries[0];
153
+ for (const entry of entries) {
154
+ const weight = entry.weight / max;
155
+ if (weight === 0)
156
+ continue;
157
+ cumulative += weight;
158
+ last = entry;
159
+ if (target < cumulative)
160
+ return result(entry);
161
+ }
162
+ return result(last);
62
163
  }
63
- /** Pick `k` items. When `replacement` is false sampling is without replacement */
164
+ /** Sample with replacement by default; otherwise return up to k distinct entries. */
64
165
  function pickMany(options, k, cfg = {}) {
65
- const { replacement = true, ...rest } = cfg;
166
+ validateCount(k);
167
+ const { replacement = true } = cfg;
168
+ if (typeof replacement !== 'boolean')
169
+ throw new TypeError('replacement must be a boolean');
170
+ const config = resolveConfig(cfg);
171
+ const entries = validateOptions(options);
66
172
  if (replacement) {
67
- return Array.from({ length: k }, () => weightedPick(options, rest));
173
+ const draw = buildDraw(entries, config, 'cdf');
174
+ return Array.from({ length: k }, draw);
68
175
  }
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 }));
176
+ validateTotal(entries, config);
177
+ if (k === 0)
178
+ return [];
179
+ // Log-space exponential race avoids power underflow/overflow for extreme weights.
180
+ // A uniform value of zero corresponds to infinite waiting time.
181
+ const ranked = entries.filter(entry => entry.weight > 0).map(entry => ({
182
+ entry,
183
+ key: Math.log(-Math.log(random(config.rng))) - Math.log(entry.weight),
184
+ }));
185
+ ranked.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
186
+ return ranked.slice(0, k).map(({ entry }) => result(entry));
84
187
  }
85
- /** Create a weighted picker for many fast selections */
188
+ /** Prepare reusable lookup tables for repeated selections. */
86
189
  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;
190
+ const { method = 'alias' } = cfg;
191
+ if (method !== 'alias' && method !== 'cdf')
192
+ throw new TypeError('Unknown picker method');
193
+ const config = resolveConfig(cfg);
194
+ let entries = validateOptions(options);
195
+ let draw = buildDraw(entries, config, method);
196
+ const indices = new Map();
197
+ entries.forEach((entry, index) => {
198
+ if (!indices.has(entry.id))
199
+ indices.set(entry.id, index);
200
+ });
201
+ function updateWeights(updates) {
202
+ if (!Array.isArray(updates))
203
+ throw new TypeError('updates must be an array');
204
+ if (updates.length === 0)
205
+ return;
206
+ const next = entries.slice();
207
+ for (const { id, weight } of updates) {
208
+ const index = indices.get(id);
209
+ if (index === undefined)
210
+ throw new TypeError('ID not found');
211
+ validateWeight(weight);
212
+ next[index] = { ...next[index], weight };
148
213
  }
149
- return { id: opts[low].id, item: opts[low].item };
150
- };
214
+ const nextDraw = buildDraw(next, config, method);
215
+ entries = next;
216
+ draw = nextDraw;
217
+ }
151
218
  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();
219
+ pick: () => draw(),
220
+ pickMany: (k) => {
221
+ validateCount(k);
222
+ return Array.from({ length: k }, () => draw());
163
223
  },
224
+ updateWeight: (id, weight) => updateWeights([{ id, weight }]),
225
+ updateWeights,
164
226
  };
165
227
  }
166
228
  exports.default = weightedPick;
@@ -1,4 +1,2 @@
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;
1
+ export { default, weightedPick, pickMany, createWeightedPicker } from './weightList.js';
2
+ export type { RNG, PickConfig, SampleConfig, PickerConfig, Method, WeightedInput, WeightedResult, WeightedPicker, } from './weightList.js';
package/dist/esm/index.js CHANGED
@@ -1,5 +1 @@
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;
1
+ export { default, weightedPick, pickMany, createWeightedPicker } from './weightList.js';
@@ -1,12 +1,10 @@
1
- /** RNG function returning a float x where 0 <= x < 1 */
1
+ /** Uniform random number in [0, 1). */
2
2
  export type RNG = () => number;
3
- /** Configuration shared by all pickers */
4
3
  export interface PickConfig {
5
- /** Normalize weights so that they sum 1. Defaults to `true` */
4
+ /** Accept relative weights. Defaults to true. */
6
5
  normalize?: boolean;
7
- /** Tolerance when checking weight sums. Defaults to `1e-12` */
6
+ /** Absolute tolerance for a sum of 1 in strict mode. Defaults to 1e-12. */
8
7
  epsilon?: number;
9
- /** Random number generator. Defaults to crypto or `Math.random` */
10
8
  rng?: RNG;
11
9
  }
12
10
  export interface WeightedInput<T> {
@@ -18,19 +16,27 @@ export interface WeightedResult<T> {
18
16
  id: number;
19
17
  item: T;
20
18
  }
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
19
  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 & {
20
+ export interface SampleConfig extends PickConfig {
21
+ replacement?: boolean;
22
+ }
23
+ export interface PickerConfig extends PickConfig {
30
24
  method?: Method;
31
- }): {
32
- pick: () => WeightedResult<T>;
33
- pickMany: (k: number) => WeightedResult<T>[];
34
- updateWeight: (id: number, weight: number) => void;
35
- };
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>;
36
42
  export default weightedPick;