random-weighted-pick 1.0.12 → 2.0.1

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.
Files changed (43) hide show
  1. package/.circleci/config.yml +1 -1
  2. package/.eslintrc.json +7 -0
  3. package/.local-tests/esm-smoke/package-lock.json +25 -0
  4. package/.local-tests/esm-smoke/package.json +16 -0
  5. package/.local-tests/esm-smoke/test.mjs +52 -0
  6. package/.local-tests/npm-smoke/package-lock.json +25 -0
  7. package/.local-tests/npm-smoke/package.json +15 -0
  8. package/.local-tests/npm-smoke/test.js +61 -0
  9. package/.prettierrc +4 -0
  10. package/CONTRIBUTING.md +9 -0
  11. package/README.md +144 -45
  12. package/dist/cjs/index.js +45 -0
  13. package/dist/cjs/package.json +1 -0
  14. package/dist/cjs/weightList.js +166 -0
  15. package/dist/esm/index.d.ts +4 -0
  16. package/dist/esm/index.js +7 -0
  17. package/dist/esm/weightList.d.ts +36 -0
  18. package/dist/esm/weightList.js +161 -0
  19. package/jest.config.cjs +5 -0
  20. package/package.json +22 -32
  21. package/random-weighted-pick-2.0.0.tgz +0 -0
  22. package/random-weighted-pick-2.0.1.tgz +0 -0
  23. package/tsconfig.cjs.json +8 -0
  24. package/tsconfig.esm.json +9 -0
  25. package/tsconfig.json +20 -0
  26. package/.eslintrc +0 -27
  27. package/coverage/clover.xml +0 -54
  28. package/coverage/coverage-final.json +0 -3
  29. package/coverage/lcov-report/base.css +0 -212
  30. package/coverage/lcov-report/index.html +0 -106
  31. package/coverage/lcov-report/prettify.css +0 -1
  32. package/coverage/lcov-report/prettify.js +0 -1
  33. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  34. package/coverage/lcov-report/sorter.js +0 -158
  35. package/coverage/lcov-report/src/index.html +0 -93
  36. package/coverage/lcov-report/src/utils/index.html +0 -93
  37. package/coverage/lcov-report/src/utils/tests.utils.js.html +0 -128
  38. package/coverage/lcov-report/src/weightList.js.html +0 -194
  39. package/coverage/lcov.info +0 -106
  40. package/dist/index.js +0 -1
  41. package/scripts/emptyFolder.js +0 -18
  42. package/webpack.config.js +0 -46
  43. package/webpack.prod.config.js +0 -31
@@ -2,7 +2,7 @@ version: 2
2
2
  jobs:
3
3
  build:
4
4
  docker:
5
- - image: circleci/node:8.9.3
5
+ - image: cimg/node:lts
6
6
  working_directory: ~/random-weighted-pick
7
7
 
8
8
  steps:
package/.eslintrc.json ADDED
@@ -0,0 +1,7 @@
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
+ }
@@ -0,0 +1,25 @@
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
+ }
@@ -0,0 +1,16 @@
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
+ }
@@ -0,0 +1,52 @@
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
+
@@ -0,0 +1,25 @@
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
+ }
@@ -0,0 +1,15 @@
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
+ }
@@ -0,0 +1,61 @@
1
+ /* Smoke test for random-weighted-pick (CJS) */
2
+ const lib = require('random-weighted-pick')
3
+
4
+ // Library should expose default function and named exports
5
+ if (typeof lib !== 'function') {
6
+ console.error('Default export is not a function')
7
+ process.exit(1)
8
+ }
9
+
10
+ const { weightedPick, pickMany, createWeightedPicker } = lib
11
+
12
+ if (typeof weightedPick !== 'function' || typeof pickMany !== 'function' || typeof createWeightedPicker !== 'function') {
13
+ console.error('Named exports missing')
14
+ process.exit(1)
15
+ }
16
+
17
+ const options = [
18
+ { id: 0, weight: 0.2, item: 'A' },
19
+ { id: 1, weight: 0.3, item: 'B' },
20
+ { id: 2, weight: 0.5, item: 'C' },
21
+ ]
22
+
23
+ // Deterministic RNG for repeatability
24
+ let i = 0
25
+ const values = [0.05, 0.35, 0.85, 0.49, 0.51]
26
+ const rng = () => values[i++ % values.length]
27
+
28
+ // Single pick via default export
29
+ const one = lib(options, { rng })
30
+ console.log('one:', one)
31
+
32
+ // Single pick via named export
33
+ const one2 = weightedPick(options, { rng })
34
+ console.log('one2:', one2)
35
+
36
+ // Many picks
37
+ const many = pickMany(options, 3, { rng })
38
+ console.log('many:', many)
39
+
40
+ // Picker API
41
+ const picker = createWeightedPicker(options, { method: 'alias', rng })
42
+ const p1 = picker.pick()
43
+ const p2 = picker.pick()
44
+ const many2 = picker.pickMany(2)
45
+ console.log('picker:', { p1, p2, many2 })
46
+
47
+ // Basic assertions
48
+ const assertResult = r => {
49
+ if (!r || typeof r.id !== 'number' || !['A', 'B', 'C'].includes(r.item)) {
50
+ throw new Error('Invalid result shape: ' + JSON.stringify(r))
51
+ }
52
+ }
53
+
54
+ assertResult(one)
55
+ assertResult(one2)
56
+ many.forEach(assertResult)
57
+ many2.forEach(assertResult)
58
+
59
+ console.log('Smoke test passed.')
60
+
61
+
package/.prettierrc ADDED
@@ -0,0 +1,4 @@
1
+ {
2
+ "singleQuote": true,
3
+ "semi": false
4
+ }
@@ -0,0 +1,9 @@
1
+ # Contributing
2
+
3
+ ## Development Setup
4
+
5
+ 1. Install dependencies: `npm install`
6
+ 2. Run tests: `npm test`
7
+ 3. Build the library: `npm run build`
8
+
9
+ Please make sure tests and build pass before submitting a pull request.
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
- this module has no external dependencies and is licensed under the MIT License.
3
+ [![npm](https://img.shields.io/npm/v/random-weighted-pick.svg)](https://www.npmjs.com/package/random-weighted-pick)
4
+ [![downloads](https://img.shields.io/npm/dm/random-weighted-pick.svg)](https://www.npmjs.com/package/random-weighted-pick)
5
+ [![bundle size](https://img.shields.io/bundlephobia/minzip/random-weighted-pick.svg)](https://bundlephobia.com/package/random-weighted-pick)
6
+ ![types](https://img.shields.io/badge/types-TypeScript-3178C6?logo=typescript)
7
+ ![module](https://img.shields.io/badge/module-ESM%20%26%20CJS-2ea44f)
8
+ ![node](https://img.shields.io/node/v/random-weighted-pick.svg)
9
+ ![deps](https://img.shields.io/badge/deps-0-brightgreen)
10
+ [![license](https://img.shields.io/npm/l/random-weighted-pick.svg)](./LICENSE)
5
11
 
6
- ![](https://circleci.com/gh/phellipeandrade/random-weighted-pick.svg?circle-token=419638ce524623e596d38a5ce25953266255c9a4)
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
- ![](http://img.badgesize.io/https://raw.githubusercontent.com/phellipeandrade/random-weighted-pick/master/dist/index.js) [![codebeat badge](https://codebeat.co/badges/2472237c-3e96-4098-928f-9762db4b2b4d)](https://codebeat.co/projects/github-com-phellipeandrade-random-weighted-pick-master-71204f75-a323-42b3-a9c3-7ba40dfbdb83)
14
+ ## Installation
9
15
 
16
+ ```bash
17
+ npm install random-weighted-pick
18
+ ```
10
19
 
11
- ## Installation & Usage
12
- ### install
20
+ - **Node**: `>=16`
21
+ - Supports **ESM** and **CommonJS**.
13
22
 
14
- ```sh
15
- npm i -S random-weighted-pick
16
- ```
23
+ ## Import
17
24
 
18
- ### usage
25
+ ```ts
26
+ // ESM
27
+ import weightedPick, { pickMany, createWeightedPicker } from 'random-weighted-pick'
19
28
 
20
- ```js
21
- import weightedPick from 'random-weighted-pick'
22
- // OR
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
- ```js
34
+ ## Quick start
27
35
 
36
+ ```ts
28
37
  const options = [
29
- { id: 0, weight: 0.2, item: () => console.log('Lemon') },
30
- { id: 1, weight: 0.3, item: ['Grape', 'Orange', 'Apple'] },
31
- { id: 2, weight: 0.4, item: 'Mango' },
32
- { id: 3, weight: 0.1, item: 3 }
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
- const result = weightedPick(options)
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
- console.log(result) // { id: 2, item: 'Mango' }
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
- ## Development
43
- ### install
44
- `npm install`
59
+ ## API
45
60
 
46
- Dependency module install
47
- ### build
61
+ ### `weightedPick(options, config?) => { id: number, item: T }`
62
+ Pick 1 item according to its weight.
48
63
 
49
- `npm run build`
64
+ ### `pickMany(options, k, config?) => Array<{ id: number, item: T }>`
65
+ Pick `k` items. When `replacement: false`, sampling is without replacement.
50
66
 
51
- Do some magic with ES6 to create ES5 code.
67
+ ### `createWeightedPicker(options, config?)`
68
+ Create an optimized picker for multiple selections.
52
69
 
53
- ### test
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
- `npm run test`
75
+ ## Types
56
76
 
57
- Run test with [Jest](https://facebook.github.io/jest/) + [Chai](http://chaijs.com)
77
+ ```ts
78
+ export interface WeightedInput<T> {
79
+ id?: number
80
+ weight: number
81
+ item: T
82
+ }
58
83
 
59
- ### develop
60
- `npm run dev` : Run develop server
84
+ export interface WeightedResult<T> {
85
+ id: number
86
+ item: T
87
+ }
61
88
 
62
- You can see result in
89
+ export type RNG = () => number
63
90
 
64
- * OS X : http://0.0.0.0:8080,
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
- * Windows : http://localhost:8080
97
+ export type Method = 'cdf' | 'alias'
98
+ ```
67
99
 
68
- ## List of available tasks
100
+ - `pickMany` also accepts `{ replacement?: boolean }`.
101
+ - `createWeightedPicker` accepts `{ method?: 'cdf' | 'alias' }`.
69
102
 
70
- ### clean
103
+ ## Options and behavior
71
104
 
72
- `rm -f dist/*`
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
- Delete existing dist files
109
+ ## Advanced examples
75
110
 
76
- ## License
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
- Copyright (c) 2016 KossHackaton OneTeam
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,45 @@
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_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
+ }
@@ -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;