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.
@@ -1,161 +1,223 @@
1
- const throwTypeError = (msg) => {
2
- throw new TypeError(msg);
3
- };
1
+ const randomWords = new Uint32Array(2);
4
2
  const defaultRNG = () => {
5
- if (typeof globalThis !== 'undefined' && globalThis.crypto?.getRandomValues) {
6
- const arr = new Uint32Array(1);
7
- globalThis.crypto.getRandomValues(arr);
8
- return arr[0] / 0x100000000;
3
+ if (typeof globalThis.crypto?.getRandomValues === 'function') {
4
+ globalThis.crypto.getRandomValues(randomWords);
5
+ return ((randomWords[0] >>> 11) * 0x100000000 + randomWords[1]) / 0x20000000000000;
9
6
  }
10
7
  return Math.random();
11
8
  };
12
- const validateOptions = (options) => {
9
+ function resolveConfig(cfg) {
10
+ const { normalize = true, epsilon = 1e-12, rng = defaultRNG } = cfg;
11
+ if (typeof normalize !== 'boolean')
12
+ throw new TypeError('normalize must be a boolean');
13
+ if (!Number.isFinite(epsilon) || epsilon < 0) {
14
+ throw new TypeError('epsilon must be a finite non-negative number');
15
+ }
16
+ if (typeof rng !== 'function')
17
+ throw new TypeError('rng must be a function');
18
+ return { normalize, epsilon, rng };
19
+ }
20
+ function random(rng) {
21
+ const value = rng();
22
+ if (!Number.isFinite(value) || value < 0 || value >= 1) {
23
+ throw new TypeError('RNG should return a number x where 0 <= x < 1');
24
+ }
25
+ return value;
26
+ }
27
+ function validateWeight(weight) {
28
+ if (!Number.isFinite(weight) || weight < 0) {
29
+ throw new TypeError('Weights should be finite numbers >= 0');
30
+ }
31
+ }
32
+ function validateCount(k) {
33
+ if (!Number.isSafeInteger(k) || k < 0 || k > 0xffffffff) {
34
+ throw new RangeError('k must be a non-negative integer within the array length limit');
35
+ }
36
+ }
37
+ function validateOptions(options) {
13
38
  if (!Array.isArray(options)) {
14
- return throwTypeError('Weighted List expect Array of Objects as argument');
39
+ throw new TypeError('Weighted List expect Array of Objects as argument');
15
40
  }
16
- return options.map((opt, i) => {
17
- if (!('weight' in opt))
18
- throwTypeError('Every list item should have [weight] property');
19
- if (!('item' in opt))
20
- throwTypeError('Every list item should have [item] property');
21
- const w = opt.weight;
22
- if (typeof w !== 'number' || Number.isNaN(w) || !Number.isFinite(w) || w < 0) {
23
- throwTypeError('Weights should be finite numbers >= 0');
41
+ return Array.from(options, (option, index) => {
42
+ if (option === null || typeof option !== 'object') {
43
+ throw new TypeError('Every list item should be an object');
24
44
  }
25
- return { id: opt.id ?? i, item: opt.item, weight: w };
45
+ if (!('weight' in option))
46
+ throw new TypeError('Every list item should have [weight] property');
47
+ if (!('item' in option))
48
+ throw new TypeError('Every list item should have [item] property');
49
+ const weight = option.weight;
50
+ validateWeight(weight);
51
+ const id = option.id ?? index;
52
+ if (!Number.isFinite(id))
53
+ throw new TypeError('ID must be a finite number');
54
+ return { id, item: option.item, weight };
26
55
  });
27
- };
28
- const normalize = (weights, { normalize, epsilon }) => {
29
- const total = weights.reduce((a, b) => a + b, 0);
30
- if (normalize) {
31
- if (total <= epsilon)
32
- throwTypeError("Sum of 'weights' should be greater than 0");
33
- return weights.map((w) => w / total);
56
+ }
57
+ function validateTotal(entries, config) {
58
+ let max = 0;
59
+ let total = 0;
60
+ for (const entry of entries) {
61
+ max = Math.max(max, entry.weight);
62
+ if (!config.normalize)
63
+ total += entry.weight;
34
64
  }
35
- if (Math.abs(total - 1) > epsilon)
36
- throwTypeError("Sum of 'weights' should be equal 1");
37
- return weights;
38
- };
39
- /** Pick a single item based on its weight */
40
- export function weightedPick(options, cfg = {}) {
41
- const config = { normalize: true, epsilon: 1e-12, rng: defaultRNG, ...cfg };
42
- const opts = validateOptions(options);
43
- const weights = opts.map(o => o.weight);
44
- const normalized = normalize(weights, config);
45
- const num = config.rng();
46
- if (typeof num !== 'number' || Number.isNaN(num) || num < 0 || num >= 1) {
47
- throwTypeError('RNG should return a number x where 0 <= x < 1');
65
+ if (max === 0)
66
+ throw new TypeError("Sum of 'weights' should be greater than 0");
67
+ if (!config.normalize && (!Number.isFinite(total) || Math.abs(total - 1) > config.epsilon)) {
68
+ throw new TypeError("Sum of 'weights' should be equal 1");
48
69
  }
49
- let acc = 0;
50
- for (let i = 0; i < normalized.length; i++) {
51
- acc += normalized[i];
52
- if (num < acc) {
53
- return { id: opts[i].id, item: opts[i].item };
54
- }
70
+ return max;
71
+ }
72
+ function result(entry) {
73
+ return { id: entry.id, item: entry.item };
74
+ }
75
+ /** Scale before summing to avoid overflow and retain small absolute weights. */
76
+ function distribution(entries, config) {
77
+ const max = validateTotal(entries, config);
78
+ const active = [];
79
+ const cumulative = [];
80
+ const scaled = [];
81
+ let total = 0;
82
+ for (const entry of entries) {
83
+ const weight = entry.weight / max;
84
+ if (weight === 0)
85
+ continue;
86
+ total += weight;
87
+ active.push(entry);
88
+ scaled.push(weight);
89
+ cumulative.push(total);
90
+ }
91
+ return { active, cumulative, scaled, total };
92
+ }
93
+ function buildDraw(entries, config, method) {
94
+ const { active, cumulative, scaled, total } = distribution(entries, config);
95
+ if (method === 'cdf') {
96
+ return () => {
97
+ const target = random(config.rng) * total;
98
+ let low = 0;
99
+ let high = cumulative.length - 1;
100
+ while (low < high) {
101
+ const mid = low + Math.floor((high - low) / 2);
102
+ if (target < cumulative[mid])
103
+ high = mid;
104
+ else
105
+ low = mid + 1;
106
+ }
107
+ return result(active[low]);
108
+ };
55
109
  }
56
- return { id: opts[opts.length - 1].id, item: opts[opts.length - 1].item };
110
+ const n = active.length;
111
+ const probabilities = new Float64Array(n);
112
+ const aliases = new Uint32Array(n);
113
+ const small = [];
114
+ const large = [];
115
+ for (let i = 0; i < n; i++) {
116
+ scaled[i] = (scaled[i] / total) * n;
117
+ (scaled[i] < 1 ? small : large).push(i);
118
+ }
119
+ while (small.length && large.length) {
120
+ const l = small.pop();
121
+ const g = large.pop();
122
+ probabilities[l] = scaled[l];
123
+ aliases[l] = g;
124
+ scaled[g] = (scaled[g] + scaled[l]) - 1;
125
+ (scaled[g] < 1 ? small : large).push(g);
126
+ }
127
+ for (const index of small)
128
+ probabilities[index] = 1;
129
+ for (const index of large)
130
+ probabilities[index] = 1;
131
+ return () => {
132
+ const index = Math.min(Math.floor(random(config.rng) * n), n - 1);
133
+ const coin = random(config.rng);
134
+ return result(active[coin < probabilities[index] ? index : aliases[index]]);
135
+ };
136
+ }
137
+ /** Select one entry with probability proportional to its weight. */
138
+ export function weightedPick(options, cfg = {}) {
139
+ const config = resolveConfig(cfg);
140
+ const entries = validateOptions(options);
141
+ const max = validateTotal(entries, config);
142
+ let total = 0;
143
+ for (const entry of entries)
144
+ total += entry.weight / max;
145
+ const target = random(config.rng) * total;
146
+ let cumulative = 0;
147
+ let last = entries[0];
148
+ for (const entry of entries) {
149
+ const weight = entry.weight / max;
150
+ if (weight === 0)
151
+ continue;
152
+ cumulative += weight;
153
+ last = entry;
154
+ if (target < cumulative)
155
+ return result(entry);
156
+ }
157
+ return result(last);
57
158
  }
58
- /** Pick `k` items. When `replacement` is false sampling is without replacement */
159
+ /** Sample with replacement by default; otherwise return up to k distinct entries. */
59
160
  export function pickMany(options, k, cfg = {}) {
60
- const { replacement = true, ...rest } = cfg;
161
+ validateCount(k);
162
+ const { replacement = true } = cfg;
163
+ if (typeof replacement !== 'boolean')
164
+ throw new TypeError('replacement must be a boolean');
165
+ const config = resolveConfig(cfg);
166
+ const entries = validateOptions(options);
61
167
  if (replacement) {
62
- return Array.from({ length: k }, () => weightedPick(options, rest));
168
+ const draw = buildDraw(entries, config, 'cdf');
169
+ return Array.from({ length: k }, draw);
63
170
  }
64
- const config = { normalize: true, epsilon: 1e-12, rng: defaultRNG, ...rest };
65
- const opts = validateOptions(options);
66
- const res = [];
67
- opts.forEach((o) => {
68
- const r = config.rng();
69
- if (typeof r !== 'number' || Number.isNaN(r) || r <= 0 || r >= 1) {
70
- throwTypeError('RNG should return a number x where 0 < x < 1');
71
- }
72
- if (o.weight > 0) {
73
- const key = Math.pow(r, 1 / o.weight);
74
- res.push({ key, option: o });
75
- }
76
- });
77
- res.sort((a, b) => b.key - a.key);
78
- return res.slice(0, k).map(r => ({ id: r.option.id, item: r.option.item }));
171
+ validateTotal(entries, config);
172
+ if (k === 0)
173
+ return [];
174
+ // Log-space exponential race avoids power underflow/overflow for extreme weights.
175
+ // A uniform value of zero corresponds to infinite waiting time.
176
+ const ranked = entries.filter(entry => entry.weight > 0).map(entry => ({
177
+ entry,
178
+ key: Math.log(-Math.log(random(config.rng))) - Math.log(entry.weight),
179
+ }));
180
+ ranked.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
181
+ return ranked.slice(0, k).map(({ entry }) => result(entry));
79
182
  }
80
- /** Create a weighted picker for many fast selections */
183
+ /** Prepare reusable lookup tables for repeated selections. */
81
184
  export function createWeightedPicker(options, cfg = {}) {
82
- const { method = 'alias', ...rest } = cfg;
83
- const config = { normalize: true, epsilon: 1e-12, rng: defaultRNG, ...rest };
84
- let opts = validateOptions(options);
85
- let probs = [];
86
- let alias = [];
87
- let cdf = [];
88
- const build = () => {
89
- const weights = opts.map(o => o.weight);
90
- const normalized = normalize(weights, config);
91
- if (method === 'alias') {
92
- const n = normalized.length;
93
- const scaled = normalized.map(w => w * n);
94
- const small = [];
95
- const large = [];
96
- probs = new Array(n).fill(0);
97
- alias = new Array(n).fill(0);
98
- scaled.forEach((w, i) => (w < 1 ? small : large).push(i));
99
- while (small.length && large.length) {
100
- const l = small.pop();
101
- const g = large.pop();
102
- probs[l] = scaled[l];
103
- alias[l] = g;
104
- scaled[g] = scaled[g] + scaled[l] - 1;
105
- if (scaled[g] < 1)
106
- small.push(g);
107
- else
108
- large.push(g);
109
- }
110
- ;
111
- [...large, ...small].forEach(i => (probs[i] = 1));
112
- }
113
- else {
114
- cdf = [];
115
- let sum = 0;
116
- normalized.forEach((w) => {
117
- sum += w;
118
- cdf.push(sum);
119
- });
120
- }
121
- };
122
- build();
123
- const pick = () => {
124
- if (method === 'alias') {
125
- const n = opts.length;
126
- const i = Math.floor(config.rng() * n);
127
- const r = config.rng();
128
- const idx = r < probs[i] ? i : alias[i];
129
- return { id: opts[idx].id, item: opts[idx].item };
130
- }
131
- const r = config.rng();
132
- if (typeof r !== 'number' || Number.isNaN(r) || r < 0 || r >= 1) {
133
- throwTypeError('RNG should return a number x where 0 <= x < 1');
134
- }
135
- let low = 0;
136
- let high = cdf.length - 1;
137
- while (low < high) {
138
- const mid = Math.floor((low + high) / 2);
139
- if (r < cdf[mid])
140
- high = mid;
141
- else
142
- low = mid + 1;
185
+ const { method = 'alias' } = cfg;
186
+ if (method !== 'alias' && method !== 'cdf')
187
+ throw new TypeError('Unknown picker method');
188
+ const config = resolveConfig(cfg);
189
+ let entries = validateOptions(options);
190
+ let draw = buildDraw(entries, config, method);
191
+ const indices = new Map();
192
+ entries.forEach((entry, index) => {
193
+ if (!indices.has(entry.id))
194
+ indices.set(entry.id, index);
195
+ });
196
+ function updateWeights(updates) {
197
+ if (!Array.isArray(updates))
198
+ throw new TypeError('updates must be an array');
199
+ if (updates.length === 0)
200
+ return;
201
+ const next = entries.slice();
202
+ for (const { id, weight } of updates) {
203
+ const index = indices.get(id);
204
+ if (index === undefined)
205
+ throw new TypeError('ID not found');
206
+ validateWeight(weight);
207
+ next[index] = { ...next[index], weight };
143
208
  }
144
- return { id: opts[low].id, item: opts[low].item };
145
- };
209
+ const nextDraw = buildDraw(next, config, method);
210
+ entries = next;
211
+ draw = nextDraw;
212
+ }
146
213
  return {
147
- pick,
148
- pickMany: (k) => Array.from({ length: k }, () => pick()),
149
- updateWeight: (id, weight) => {
150
- const idx = opts.findIndex(o => o.id === id);
151
- if (idx === -1)
152
- throwTypeError('ID not found');
153
- if (typeof weight !== 'number' || Number.isNaN(weight) || !Number.isFinite(weight) || weight < 0) {
154
- throwTypeError('Weights should be finite numbers >= 0');
155
- }
156
- opts[idx].weight = weight;
157
- build();
214
+ pick: () => draw(),
215
+ pickMany: (k) => {
216
+ validateCount(k);
217
+ return Array.from({ length: k }, () => draw());
158
218
  },
219
+ updateWeight: (id, weight) => updateWeights([{ id, weight }]),
220
+ updateWeights,
159
221
  };
160
222
  }
161
223
  export default weightedPick;
package/package.json CHANGED
@@ -1,35 +1,43 @@
1
1
  {
2
2
  "name": "random-weighted-pick",
3
- "version": "2.0.1",
3
+ "version": "2.1.0",
4
+ "description": "Zero-dependency weighted random sampling for TypeScript and JavaScript. Single draws, sampling without replacement, and reusable alias/CDF pickers.",
4
5
  "type": "module",
5
- "main": "dist/cjs/index.js",
6
- "types": "dist/esm/index.d.ts",
6
+ "main": "./dist/cjs/index.js",
7
+ "module": "./dist/esm/index.js",
8
+ "types": "./dist/esm/index.d.ts",
7
9
  "exports": {
8
10
  ".": {
9
- "types": "./dist/esm/index.d.ts",
10
- "import": "./dist/esm/index.js",
11
- "require": "./dist/cjs/index.js"
11
+ "import": {
12
+ "types": "./dist/esm/index.d.ts",
13
+ "default": "./dist/esm/index.js"
14
+ },
15
+ "require": {
16
+ "types": "./dist/cjs/index.d.ts",
17
+ "default": "./dist/cjs/index.js"
18
+ }
12
19
  }
13
20
  },
21
+ "files": [
22
+ "dist/",
23
+ "README.md",
24
+ "LICENSE"
25
+ ],
26
+ "sideEffects": false,
14
27
  "engines": {
15
28
  "node": ">=16"
16
29
  },
17
30
  "scripts": {
18
- "build": "tsc -p tsconfig.esm.json && tsc -p tsconfig.cjs.json && echo '{\"type\":\"commonjs\"}' > dist/cjs/package.json",
19
- "test": "jest",
20
- "coverage": "npm test -- --coverage"
31
+ "build": "node scripts/build.mjs",
32
+ "typecheck": "tsc -p tsconfig.json --noEmit",
33
+ "test": "npm run build && node --test test/weighted.test.mjs test/package.test.mjs && tsc -p test/tsconfig.json",
34
+ "coverage": "npm run build && node --experimental-test-coverage --test test/weighted.test.mjs test/package.test.mjs",
35
+ "benchmark": "npm run build && node benchmarks/pick.mjs",
36
+ "prepack": "npm run build"
21
37
  },
22
38
  "license": "MIT",
23
39
  "devDependencies": {
24
- "@types/jest": "^29.5.14",
25
- "@typescript-eslint/eslint-plugin": "^7.18.0",
26
- "@typescript-eslint/parser": "^7.18.0",
27
- "eslint": "^8.56.0",
28
- "jest": "^29.7.0",
29
- "prettier": "^3.3.3",
30
- "ts-jest": "^29.4.1",
31
- "typescript": "^5.9.2",
32
- "undici-types": "^7.16.0"
40
+ "typescript": "^5.9.3"
33
41
  },
34
42
  "repository": {
35
43
  "type": "git",
@@ -38,13 +46,18 @@
38
46
  "keywords": [
39
47
  "random",
40
48
  "weighted",
41
- "list",
42
- "node"
49
+ "sampling",
50
+ "weighted-random",
51
+ "probability",
52
+ "alias-method",
53
+ "typescript",
54
+ "random-selection",
55
+ "monte-carlo",
56
+ "load-balancing"
43
57
  ],
44
58
  "author": "Phellipe Andrade",
45
59
  "bugs": {
46
60
  "url": "https://github.com/phellipeandrade/random-weighted-pick/issues"
47
61
  },
48
- "homepage": "https://github.com/phellipeandrade/random-weighted-pick/#readme",
49
- "description": "Easily choose a random item from a weighted list of items."
62
+ "homepage": "https://github.com/phellipeandrade/random-weighted-pick#readme"
50
63
  }
package/.babelrc DELETED
@@ -1,6 +0,0 @@
1
- {
2
- "presets": ["env"],
3
- "plugins": [
4
- "add-module-exports"
5
- ]
6
- }
@@ -1,20 +0,0 @@
1
- version: 2
2
- jobs:
3
- build:
4
- docker:
5
- - image: cimg/node:lts
6
- working_directory: ~/random-weighted-pick
7
-
8
- steps:
9
- - checkout
10
- - restore_cache:
11
- keys:
12
- - v1-dependencies-{{ checksum "package.json" }}
13
- - v1-dependencies-
14
- - run: npm install
15
- - save_cache:
16
- paths:
17
- - node_modules
18
- key: v1-dependencies-{{ checksum "package.json" }}
19
- - run: npm run test
20
-
package/.eslintrc.json DELETED
@@ -1,7 +0,0 @@
1
- {
2
- "parser": "@typescript-eslint/parser",
3
- "plugins": ["@typescript-eslint"],
4
- "extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended", "prettier"],
5
- "env": { "node": true, "jest": true },
6
- "ignorePatterns": ["dist"]
7
- }
@@ -1,25 +0,0 @@
1
- {
2
- "name": "esm-smoke",
3
- "version": "1.0.0",
4
- "lockfileVersion": 3,
5
- "requires": true,
6
- "packages": {
7
- "": {
8
- "name": "esm-smoke",
9
- "version": "1.0.0",
10
- "license": "ISC",
11
- "dependencies": {
12
- "random-weighted-pick": "file:../../random-weighted-pick-2.0.0.tgz"
13
- }
14
- },
15
- "node_modules/random-weighted-pick": {
16
- "version": "2.0.0",
17
- "resolved": "file:../../random-weighted-pick-2.0.0.tgz",
18
- "integrity": "sha512-Q2BUYXnDDTv5boCpsMCgusna4Wd5OzKab0zjcrBgiZ0L8pPCYlweYwhTH3udO9YNrCZqKCygioeT21CXEdvOFA==",
19
- "license": "MIT",
20
- "engines": {
21
- "node": ">=16"
22
- }
23
- }
24
- }
25
- }
@@ -1,16 +0,0 @@
1
- {
2
- "name": "esm-smoke",
3
- "version": "1.0.0",
4
- "type": "module",
5
- "main": "test.mjs",
6
- "scripts": {
7
- "test": "node test.mjs"
8
- },
9
- "keywords": [],
10
- "author": "",
11
- "license": "ISC",
12
- "description": "",
13
- "dependencies": {
14
- "random-weighted-pick": "file:../../random-weighted-pick-2.0.0.tgz"
15
- }
16
- }
@@ -1,52 +0,0 @@
1
- /* Smoke test for random-weighted-pick (ESM) */
2
- import def, { weightedPick, pickMany, createWeightedPicker } from 'random-weighted-pick'
3
-
4
- if (typeof def !== 'function') {
5
- console.error('Default export is not a function (ESM)')
6
- process.exit(1)
7
- }
8
-
9
- if (typeof weightedPick !== 'function' || typeof pickMany !== 'function' || typeof createWeightedPicker !== 'function') {
10
- console.error('Named exports missing (ESM)')
11
- process.exit(1)
12
- }
13
-
14
- const options = [
15
- { id: 0, weight: 0.2, item: 'A' },
16
- { id: 1, weight: 0.3, item: 'B' },
17
- { id: 2, weight: 0.5, item: 'C' },
18
- ]
19
-
20
- let i = 0
21
- const values = [0.05, 0.35, 0.85, 0.49, 0.51]
22
- const rng = () => values[i++ % values.length]
23
-
24
- const one = def(options, { rng })
25
- console.log('esm:one:', one)
26
-
27
- const one2 = weightedPick(options, { rng })
28
- console.log('esm:one2:', one2)
29
-
30
- const many = pickMany(options, 3, { rng })
31
- console.log('esm:many:', many)
32
-
33
- const picker = createWeightedPicker(options, { method: 'alias', rng })
34
- const p1 = picker.pick()
35
- const p2 = picker.pick()
36
- const many2 = picker.pickMany(2)
37
- console.log('esm:picker:', { p1, p2, many2 })
38
-
39
- const assertResult = r => {
40
- if (!r || typeof r.id !== 'number' || !['A', 'B', 'C'].includes(r.item)) {
41
- throw new Error('Invalid result shape: ' + JSON.stringify(r))
42
- }
43
- }
44
-
45
- assertResult(one)
46
- assertResult(one2)
47
- many.forEach(assertResult)
48
- many2.forEach(assertResult)
49
-
50
- console.log('ESM smoke test passed.')
51
-
52
-
@@ -1,25 +0,0 @@
1
- {
2
- "name": "npm-smoke",
3
- "version": "1.0.0",
4
- "lockfileVersion": 3,
5
- "requires": true,
6
- "packages": {
7
- "": {
8
- "name": "npm-smoke",
9
- "version": "1.0.0",
10
- "license": "ISC",
11
- "dependencies": {
12
- "random-weighted-pick": "^2.0.0"
13
- }
14
- },
15
- "node_modules/random-weighted-pick": {
16
- "version": "2.0.0",
17
- "resolved": "https://registry.npmjs.org/random-weighted-pick/-/random-weighted-pick-2.0.0.tgz",
18
- "integrity": "sha512-+1W4Nzs+vOpFSUZxTULfNHBEBjRp9zgG87uim6b4oVM5NXJkBteK5+U5FHTsaQLu8Ir670scsVOWjwN0/iP5Bg==",
19
- "license": "MIT",
20
- "engines": {
21
- "node": ">=16"
22
- }
23
- }
24
- }
25
- }
@@ -1,15 +0,0 @@
1
- {
2
- "name": "npm-smoke",
3
- "version": "1.0.0",
4
- "main": "index.js",
5
- "scripts": {
6
- "test": "node test.js"
7
- },
8
- "keywords": [],
9
- "author": "",
10
- "license": "ISC",
11
- "description": "",
12
- "dependencies": {
13
- "random-weighted-pick": "^2.0.0"
14
- }
15
- }