pick-me-too 1.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/.prettierrc ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "printWidth": 120,
3
+ "trailingComma": "all",
4
+ "semi": false,
5
+ "singleQuote": true
6
+ }
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 David F. Houghton
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,183 @@
1
+ # pick-me
2
+ Generate functions that pick things from lists with specified frequencies.
3
+
4
+ ## Synopsis
5
+
6
+ ```ts
7
+ // Let's make a generator of quasi-Polynesian lorem ipsum!
8
+
9
+ import { pickMe, rando } from 'pick-me-too'
10
+
11
+ // we want our text reproducible, so we use a seeded random number generator
12
+ const rng = rando(1)
13
+
14
+ // now we specify the frequency of various patterns in our invented language
15
+
16
+ const vowels = pickMe(
17
+ [
18
+ ['a', 2],
19
+ ['e', 1],
20
+ ['i', 1.5],
21
+ ['o', 1],
22
+ ['u', 1.5],
23
+ ['ā', 0.75],
24
+ ['ē', 0.5],
25
+ ['ī', 0.75],
26
+ ['ō', 0.5],
27
+ ['ū', 0.75],
28
+ ],
29
+ rng,
30
+ )
31
+ const consonants = pickMe(
32
+ [
33
+ ["'", 5],
34
+ ['h', 1],
35
+ ['p', 3],
36
+ ['t', 3],
37
+ ['k', 3],
38
+ ['b', 1],
39
+ ['d', 1],
40
+ ['g', 1],
41
+ ['n', 3],
42
+ ['r', 1],
43
+ ],
44
+ rng,
45
+ )
46
+ // our language as simple CV syllables
47
+ const syllable = () => `${consonants()}${vowels()}`
48
+ const morphemeLength = pickMe(
49
+ [
50
+ [1, 1],
51
+ [2, 3],
52
+ [3, 1],
53
+ ],
54
+ rng,
55
+ )
56
+ const morpheme = () => {
57
+ let m = ''
58
+ for (let i = 0, lim = morphemeLength(); i < lim; i++) m += syllable()
59
+ return m
60
+ }
61
+ const reduplication = () => {
62
+ const r = morpheme()
63
+ return `${r}${r}`
64
+ }
65
+ // we can pick functions, too!
66
+ const segment = pickMe(
67
+ [
68
+ [morpheme, 5],
69
+ [reduplication, 1],
70
+ ],
71
+ rng,
72
+ )
73
+ const wordLength = pickMe(
74
+ [
75
+ [1, 5],
76
+ [2, 3],
77
+ [3, 2],
78
+ [4, 1],
79
+ [5, 1],
80
+ ],
81
+ rng,
82
+ )
83
+ const word = () => {
84
+ let w = ''
85
+ for (let i = 0, lim = wordLength(); i < lim; i++) w = w + segment()()
86
+ return w
87
+ }
88
+ const clauseLength = pickMe(
89
+ [
90
+ [1, 1],
91
+ [2, 3],
92
+ [3, 4],
93
+ [4, 4],
94
+ [5, 5],
95
+ [6, 6],
96
+ ],
97
+ rng,
98
+ )
99
+ const clause = () => {
100
+ let s = []
101
+ for (let i = 0, lim = clauseLength(); i < lim; i++) s.push(word())
102
+ return s.join(' ')
103
+ }
104
+
105
+ const saying = clause()
106
+ // => "rekātū pe'ide kēpe 'ātēdapidapi kaha"
107
+ ```
108
+
109
+ ## API
110
+
111
+ ### `function pickMe<T>(frequencies: [T, number][] | T[], rando?: () => number): () => T`
112
+
113
+ Generates a zero-argument function that returns an item from the frequency list
114
+ parameter with a probability concordant with its specified frequency.
115
+
116
+ The required parameter is a list of pairs: an item to pick and its frequency. The "frequency"
117
+ is simply a positive number which determines the probability of picking one item relative to another.
118
+ If the parameters are `[[1, 1], [2, 2]]`, you will get twice as many 2s as 1s. You will get the same
119
+ results with `[[1, 0.1], [2, 0.2]]`, `[[1, 10], [2, 20]]`, and `[[1, 0.13], [2, 0.26]]`.
120
+
121
+ The second, optional parameter is a random number sequence generator. Provide this if you want a reproducible
122
+ sequence of selections from your frequency list. If this doesn't concern you, leave it off and take
123
+ whatever `Math.random()` gives you.
124
+
125
+ If the frequency list is not a list of pairs but just a list of items, this is equivalent to a list of
126
+ pairs where all the frequencies are the same. (Note, this will not work if the items are all pairs whose
127
+ second value is a number. If you want to pick among such pairs you'll need to wrap them in new pairs.)
128
+
129
+ An item with
130
+ a non-positive frequency will be culled from the list. `pickMe` will throw an error if the list is empty.
131
+ Likewise, it will throw an error if any item appears more than once in the list. `[]` is
132
+ not good. `[[1, 1], [1, 2]]` is no better.
133
+
134
+ Note, the item returned by `pickMe` is the item you provided, not a copy. If you are picking from a list of
135
+ objects and you modify one of them, it will remain modified.
136
+
137
+ Finally, `pickMe` compiles an efficient picker from the parameters provided. As with other compiled things, such
138
+ as regular expressions, you want to do this one time in an initialization phase and then reuse it in loops.
139
+ The compilation is not terribly expensive, but skipping it altogether is cheaper.
140
+
141
+ @example
142
+ ```ts
143
+ import { rando, pickMe } from 'pick-me-too'
144
+
145
+ // make a random number generator with a seed of 1
146
+ const rng = rando(1)
147
+ const fooBarBaz = pickMe([["foo", 1], ["bar", 2], ["baz", 3]], rng)
148
+ const ar: string[] = []
149
+ for (let i = 0; i < 10; i++) ar.push(fooBarBaz())
150
+ // => [ 'baz', 'foo', 'baz', 'baz', 'baz', 'bar', 'baz', 'baz', 'bar', 'baz' ]
151
+ ```
152
+
153
+ ### `function rando(seed: number): () => number`
154
+
155
+ Generates a random number sequence generator.
156
+
157
+ This is a demonstration generator useful for testing and documentation. Any zero-argument function that returns
158
+ numbers will suffice for `pickMe`. If it returns 0 or less, the first item
159
+ given to `pickMe` will be picked. If it is 1 or less, the last item will be.
160
+
161
+ The implementation of `rando` is taken from [this Stack Overflow comment](https://stackoverflow.com/a/47593316/15060051).
162
+ There are many others if you don't find this suitable.
163
+
164
+ @example
165
+ ```ts
166
+ import { rando } from 'pick-me-too'
167
+
168
+ // make a random number generator with a seed of 1
169
+ const rng = rando(1)
170
+ const ar: number[] = []
171
+ for (let i = 0; i < 3; i++) ar.push(rng())
172
+ // => [ 0.6270739405881613, 0.002735721180215478, 0.5274470399599522 ]
173
+ ```
174
+
175
+ ## Acknowledgements
176
+
177
+ It is possible this package is a duplicate. I didn't try very hard to find out. I just felt like writing
178
+ this code and, having written it, I felt like publishing it. It may behoove you to check npmjs carefully
179
+ and compare packages.
180
+
181
+ That being said, `pickMe` should be near optimally fast (if the frequences are strongly skewed, it is
182
+ possible to compile a picker that uses fewer numerical comparisons in the typical case). Its unit and
183
+ documentation tests are thorough.
@@ -0,0 +1,14 @@
1
+ {
2
+ "transform": {
3
+ "^.+\\.(t|j)sx?$": "ts-jest"
4
+ },
5
+ "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
6
+ "moduleFileExtensions": [
7
+ "ts",
8
+ "tsx",
9
+ "js",
10
+ "jsx",
11
+ "json",
12
+ "node"
13
+ ]
14
+ }
package/lib/index.d.ts ADDED
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Generates a zero-argument function that returns an item from the frequency list
3
+ * parameter with a probability concordant with its specified frequency.
4
+ *
5
+ * The required parameter is a list of pairs: an item to pick and its frequency. The "frequency"
6
+ * is simply a positive number which determines the probability of picking one item relative to another.
7
+ * If the parameters are `[[1, 1], [2, 2]]`, you will get twice as many 2s as 1s. You will get the same
8
+ * results with `[[1, 0.1], [2, 0.2]]`, `[[1, 10], [2, 20]]`, and `[[1, 0.13], [2, 0.26]]`.
9
+ *
10
+ * If the frequency list is not a list of pairs but just a list of items, this is equivalent to a list of
11
+ * pairs where all the frequencies are the same. Note, this will not work if the items are all pairs whose
12
+ * second value is a number. If you want to pick among such pairs you'll need to wrap them each the first member
13
+ * of a frequency pair with the second value being some common positive number.
14
+ *
15
+ * An item with
16
+ * a non-positive frequency will be culled from the list. `pickMe` will throw an error if the list is empty.
17
+ * Likewise, it will throw an error if any item appears more than once in the list. `[[1, 1], [1, 2]]` is
18
+ * not good. `[[1, 1], [1,2]]` is no better.
19
+ *
20
+ * The second, optional parameter is a random number sequence generator. Provide this if you want a reproducible
21
+ * sequence of selections from your frequency list. If this doesn't concern you, leave it off and take
22
+ * whatever `Math.random()` gives you.
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * import { rando, pickMe } from 'pick-me';
27
+ *
28
+ * // make a random number generator with a seed of 1
29
+ * const rng = rando(1);
30
+ * const fooBarBaz = pickMe([["foo", 1], ["bar", 2], ["baz", 3]], rng);
31
+ * const ar: string[] = [];
32
+ * for (let i = 0; i < 10; i++) ar.push(fooBarBaz())
33
+ * // => [ 'baz', 'foo', 'baz', 'baz', 'baz', 'bar', 'baz', 'baz', 'bar', 'baz' ]
34
+ * ```
35
+ *
36
+ * @param {[T, number][] | T[]} frequencies - phrases to match
37
+ * @param {() => number} [rando=() => Math.random()] - random number generator
38
+ * @returns {() => T} a picker of T's
39
+ */
40
+ export declare function pickMe<T>(frequencies: [T, number][] | T[], rando?: () => number): () => T;
41
+ /**
42
+ * Generates a random number sequence generator. This is a demonstration generator
43
+ * useful for testing and documentation. Any zero-argument function that returns
44
+ * numbers will suffice for `pickMe`.
45
+ *
46
+ * The implementation of `rando` is taken from https://stackoverflow.com/a/47593316/15060051.
47
+ * It is the Mulberry32 algorithm.
48
+ *
49
+ * @example
50
+ * ```ts
51
+ * import { rando } from 'pick-me';
52
+ *
53
+ * // make a random number generator with a seed of 1
54
+ * const rng = rando(1);
55
+ * const ar: number[] = [];
56
+ * for (let i = 0; i < 3; i++) ar.push(rng())
57
+ * // => [ 0.6270739405881613, 0.002735721180215478, 0.5274470399599522 ]
58
+ * ```
59
+ *
60
+ * @param {number} seed - the seed for a random number sequence
61
+ * @returns {() => number} a generator of random numbers
62
+ */
63
+ export declare function rando(seed: number): () => number;
package/lib/index.js ADDED
@@ -0,0 +1,138 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.rando = exports.pickMe = void 0;
4
+ /**
5
+ * Generates a zero-argument function that returns an item from the frequency list
6
+ * parameter with a probability concordant with its specified frequency.
7
+ *
8
+ * The required parameter is a list of pairs: an item to pick and its frequency. The "frequency"
9
+ * is simply a positive number which determines the probability of picking one item relative to another.
10
+ * If the parameters are `[[1, 1], [2, 2]]`, you will get twice as many 2s as 1s. You will get the same
11
+ * results with `[[1, 0.1], [2, 0.2]]`, `[[1, 10], [2, 20]]`, and `[[1, 0.13], [2, 0.26]]`.
12
+ *
13
+ * If the frequency list is not a list of pairs but just a list of items, this is equivalent to a list of
14
+ * pairs where all the frequencies are the same. Note, this will not work if the items are all pairs whose
15
+ * second value is a number. If you want to pick among such pairs you'll need to wrap them each the first member
16
+ * of a frequency pair with the second value being some common positive number.
17
+ *
18
+ * An item with
19
+ * a non-positive frequency will be culled from the list. `pickMe` will throw an error if the list is empty.
20
+ * Likewise, it will throw an error if any item appears more than once in the list. `[[1, 1], [1, 2]]` is
21
+ * not good. `[[1, 1], [1,2]]` is no better.
22
+ *
23
+ * The second, optional parameter is a random number sequence generator. Provide this if you want a reproducible
24
+ * sequence of selections from your frequency list. If this doesn't concern you, leave it off and take
25
+ * whatever `Math.random()` gives you.
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * import { rando, pickMe } from 'pick-me';
30
+ *
31
+ * // make a random number generator with a seed of 1
32
+ * const rng = rando(1);
33
+ * const fooBarBaz = pickMe([["foo", 1], ["bar", 2], ["baz", 3]], rng);
34
+ * const ar: string[] = [];
35
+ * for (let i = 0; i < 10; i++) ar.push(fooBarBaz())
36
+ * // => [ 'baz', 'foo', 'baz', 'baz', 'baz', 'bar', 'baz', 'baz', 'bar', 'baz' ]
37
+ * ```
38
+ *
39
+ * @param {[T, number][] | T[]} frequencies - phrases to match
40
+ * @param {() => number} [rando=() => Math.random()] - random number generator
41
+ * @returns {() => T} a picker of T's
42
+ */
43
+ function pickMe(frequencies, rando) {
44
+ frequencies = sanitize(normalize(frequencies));
45
+ // short-circuit edge cases
46
+ if (frequencies.length === 0)
47
+ throw new Error(`nothing to select in ${frequencies}`);
48
+ if (frequencies.length === 1) {
49
+ const [t] = frequencies[0];
50
+ return () => t;
51
+ }
52
+ // throw an error in case of duplicates
53
+ // it is difficult to do this efficiently because we allow T to be anything
54
+ for (let i = 0, lim = frequencies.length - 1; i < lim; i++) {
55
+ const t = frequencies[i][0];
56
+ for (let j = i + 1; j < frequencies.length; j++) {
57
+ if (t === frequencies[j][0])
58
+ throw new Error(`${t} appears more than once among frequencies`);
59
+ }
60
+ }
61
+ rando !== null && rando !== void 0 ? rando : (rando = () => Math.random());
62
+ let total = 0, acc = 0;
63
+ for (const [, n] of frequencies)
64
+ total += n;
65
+ for (let i = 0; i < frequencies.length; i++) {
66
+ const [, n] = frequencies[i];
67
+ acc += n;
68
+ frequencies[i][1] = acc / total;
69
+ }
70
+ const items = [], thresholds = [];
71
+ for (const [t, n] of frequencies) {
72
+ items.push(t);
73
+ thresholds.push(n);
74
+ }
75
+ const f = thresholder(thresholds);
76
+ return () => items[f(rando())];
77
+ }
78
+ exports.pickMe = pickMe;
79
+ // take in an array of ambiguous type and return a list of pairs, T and frequency
80
+ function normalize(frequencies) {
81
+ if (frequencies.length === 0)
82
+ return frequencies;
83
+ if (frequencies.every((s) => Array.isArray(s) && s.length === 2 && typeof s[1] === 'number'))
84
+ return frequencies;
85
+ const ar = frequencies.map((t) => [t, 1]);
86
+ return ar;
87
+ }
88
+ // remove impossible frequencies
89
+ function sanitize(frequencies) {
90
+ return frequencies.map(([t, n]) => [t, Number(n)]).filter(([, n]) => Number.isFinite(n) && n > 0);
91
+ }
92
+ // make a function that converts a random number into an index, preserving the frequencies
93
+ // assuming the random number is from an even distribution in the interval [0, 1]
94
+ function thresholder(thresholds) {
95
+ return eval(`(n) => ${portion(thresholds, 0, thresholds.length)}`);
96
+ }
97
+ // recursively convert the threshold list into nested ternary operators
98
+ // this allows us to find our index in O(log(n)) comparisons
99
+ function portion(thresholds, start, end) {
100
+ const n = end - start;
101
+ if (n === 1)
102
+ return start.toString();
103
+ const i = start + (n % 2 === 0 ? n / 2 - 1 : (n - 1) / 2);
104
+ return `(n > ${thresholds[i]} ? ${portion(thresholds, i + 1, end)} : ${portion(thresholds, start, i + 1)})`;
105
+ }
106
+ // return a generator of a reproducible random number sequence
107
+ // gotten from https://stackoverflow.com/a/47593316/15060051 -- this is Mulberry32
108
+ /**
109
+ * Generates a random number sequence generator. This is a demonstration generator
110
+ * useful for testing and documentation. Any zero-argument function that returns
111
+ * numbers will suffice for `pickMe`.
112
+ *
113
+ * The implementation of `rando` is taken from https://stackoverflow.com/a/47593316/15060051.
114
+ * It is the Mulberry32 algorithm.
115
+ *
116
+ * @example
117
+ * ```ts
118
+ * import { rando } from 'pick-me';
119
+ *
120
+ * // make a random number generator with a seed of 1
121
+ * const rng = rando(1);
122
+ * const ar: number[] = [];
123
+ * for (let i = 0; i < 3; i++) ar.push(rng())
124
+ * // => [ 0.6270739405881613, 0.002735721180215478, 0.5274470399599522 ]
125
+ * ```
126
+ *
127
+ * @param {number} seed - the seed for a random number sequence
128
+ * @returns {() => number} a generator of random numbers
129
+ */
130
+ function rando(seed) {
131
+ return () => {
132
+ let t = (seed += 0x6d2b79f5);
133
+ t = Math.imul(t ^ (t >>> 15), t | 1);
134
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
135
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
136
+ };
137
+ }
138
+ exports.rando = rando;
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "pick-me-too",
3
+ "version": "1.0.0",
4
+ "description": "Generate a function that returns random items from a list with specified frequencies.",
5
+ "main": "lib/index.js",
6
+ "types": "lib/index.d.ts",
7
+ "scripts": {
8
+ "test": "jest --config jestconfig.json",
9
+ "build": "tsc"
10
+ },
11
+ "keywords": [
12
+ "frequency",
13
+ "random",
14
+ "list",
15
+ "pick"
16
+ ],
17
+ "author": {
18
+ "name": "David F. Houghton",
19
+ "url": "https://github.com/dfhoughton"
20
+ },
21
+ "license": "MIT",
22
+ "homepage": "https://github.com/dfhoughton/pick-me",
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "https://github.com/dfhoughton/pick-me"
26
+ },
27
+ "devDependencies": {
28
+ "@types/jest": "^27.4.1",
29
+ "eslint": "^8.13.0",
30
+ "eslint-config-prettier": "^8.5.0",
31
+ "jest": "^27.5.1",
32
+ "prettier": "^2.6.2",
33
+ "ts-jest": "^27.1.4",
34
+ "typescript": "^4.6.3"
35
+ }
36
+ }
@@ -0,0 +1,123 @@
1
+ /** tests for all the code shown in documentation */
2
+
3
+ import { rando, pickMe } from '..'
4
+
5
+ describe('README', () => {
6
+ describe('Synopsis', () => {
7
+ const rng = rando(1)
8
+ const vowels = pickMe(
9
+ [
10
+ ['a', 2],
11
+ ['e', 1],
12
+ ['i', 1.5],
13
+ ['o', 1],
14
+ ['u', 1.5],
15
+ ['ā', 0.75],
16
+ ['ē', 0.5],
17
+ ['ī', 0.75],
18
+ ['ō', 0.5],
19
+ ['ū', 0.75],
20
+ ],
21
+ rng,
22
+ )
23
+ const consonants = pickMe(
24
+ [
25
+ ["'", 5],
26
+ ['h', 1],
27
+ ['p', 3],
28
+ ['t', 3],
29
+ ['k', 3],
30
+ ['b', 1],
31
+ ['d', 1],
32
+ ['g', 1],
33
+ ['n', 3],
34
+ ['r', 1],
35
+ ],
36
+ rng,
37
+ )
38
+ const syllable = () => `${consonants()}${vowels()}`
39
+ const morphemeLength = pickMe(
40
+ [
41
+ [1, 1],
42
+ [2, 3],
43
+ [3, 1],
44
+ ],
45
+ rng,
46
+ )
47
+ const morpheme = () => {
48
+ let m = ''
49
+ for (let i = 0, lim = morphemeLength(); i < lim; i++) m += syllable()
50
+ return m
51
+ }
52
+ const reduplication = () => {
53
+ const r = morpheme()
54
+ return `${r}${r}`
55
+ }
56
+ const segment = pickMe(
57
+ [
58
+ [morpheme, 5],
59
+ [reduplication, 1],
60
+ ],
61
+ rng,
62
+ )
63
+ const wordLength = pickMe(
64
+ [
65
+ [1, 5],
66
+ [2, 3],
67
+ [3, 2],
68
+ [4, 1],
69
+ [5, 1],
70
+ ],
71
+ rng,
72
+ )
73
+ const word = () => {
74
+ let w = ''
75
+ for (let i = 0, lim = wordLength(); i < lim; i++) w = w + segment()()
76
+ return w
77
+ }
78
+ const clauseLength = pickMe(
79
+ [
80
+ [1, 1],
81
+ [2, 3],
82
+ [3, 4],
83
+ [4, 4],
84
+ [5, 5],
85
+ [6, 6],
86
+ ],
87
+ rng,
88
+ )
89
+ const clause = () => {
90
+ let s = []
91
+ for (let i = 0, lim = clauseLength(); i < lim; i++) s.push(word())
92
+ return s.join(' ')
93
+ }
94
+ const saying = clause()
95
+ console.log(saying)
96
+ test('polynesianish', () => expect(saying).toEqual("rekātū pe'ide kēpe 'ātēdapidapi kaha"))
97
+ })
98
+ })
99
+
100
+ describe('index.ts', () => {
101
+ describe('pickMe', () => {
102
+ const rng = rando(1)
103
+ const fooBarBaz = pickMe(
104
+ [
105
+ ['foo', 1],
106
+ ['bar', 2],
107
+ ['baz', 3],
108
+ ],
109
+ rng,
110
+ )
111
+ const ar: string[] = []
112
+ for (let i = 0; i < 10; i++) ar.push(fooBarBaz())
113
+ test('pickMe', () => expect(ar).toEqual(['baz', 'foo', 'baz', 'baz', 'baz', 'bar', 'baz', 'baz', 'bar', 'baz']))
114
+ })
115
+ describe('rando', () => {
116
+ const rng = rando(1)
117
+ const ar: number[] = []
118
+ for (let i = 0; i < 3; i++) ar.push(rng())
119
+ test('rando', () => {
120
+ expect(ar).toEqual([0.6270739405881613, 0.002735721180215478, 0.5274470399599522])
121
+ })
122
+ })
123
+ })
@@ -0,0 +1,106 @@
1
+ import { pickMe, rando } from '..'
2
+
3
+ // we need a fixed random number sequence for testing
4
+ const rng = rando(1)
5
+
6
+ describe('rando', () => {
7
+ const bins: number[] = []
8
+ for (let i = 0; i < 100; i++) {
9
+ bins[i] = 0
10
+ }
11
+ for (let i = 0, lim = bins.length * 1000; i < lim; i++) {
12
+ let idx = Math.floor(rng() * 100)
13
+ if (idx === 100) idx = 99
14
+ bins[idx] += 1
15
+ }
16
+ for (let i = 0; i < bins.length; i++) {
17
+ test('even distribution', () => expect(Math.round(bins[i] / 1000)).toEqual(1))
18
+ }
19
+ })
20
+
21
+ describe('pickMe', () => {
22
+ const trueFalse = pickMe(
23
+ [
24
+ ['true', 1],
25
+ ['false', 1],
26
+ ],
27
+ rng,
28
+ )
29
+ for (let i = 0; i < 10; i++) {
30
+ test('returns either "true" or "false"', () => expect(['true', 'false'].indexOf(trueFalse())).toBeGreaterThan(-1))
31
+ }
32
+ test('requires some items', () =>
33
+ expect(() => {
34
+ pickMe([])
35
+ }).toThrowError())
36
+ test('we allow no duplicates', () =>
37
+ expect(() => {
38
+ pickMe([
39
+ ['foo', 1],
40
+ ['foo', 1],
41
+ ])
42
+ }).toThrowError())
43
+ let f = pickMe([['foo', 1]], rng)
44
+ let ar: string[] = []
45
+ for (let i = 0; i < 100; i++) ar.push(f())
46
+ test("we always get the same thing if there's just one item", () =>
47
+ expect(ar.every((s) => s === 'foo')).toEqual(true))
48
+ f = pickMe([
49
+ ['foo', 1],
50
+ ['bar', 0],
51
+ ['baz', -1],
52
+ ])
53
+ ar.length = 0
54
+ for (let i = 0; i < 100; i++) ar.push(f())
55
+ test('we always get the same thing if only one item has a positive frequency', () =>
56
+ expect(ar.every((s) => s === 'foo')).toEqual(true))
57
+ f = pickMe(
58
+ [
59
+ ['foo', 2],
60
+ ['bar', 1],
61
+ ],
62
+ rng,
63
+ )
64
+ const counts1: Record<string, number> = { foo: 0, bar: 0 }
65
+ for (let i = 0; i < 1000; i++) counts1[f()] += 1
66
+ test('we expect some foos', () => expect(counts1.foo).toBeGreaterThan(0))
67
+ test('we expect some bars', () => expect(counts1.bar).toBeGreaterThan(0))
68
+ test('we get roughly as many of each thing as we expect', () =>
69
+ expect(Math.round(counts1.foo / counts1.bar)).toEqual(2))
70
+ // do this with a bit more rigor
71
+ const letters = 'abcdefghijklmnopqrstuvwxyz'.split('')
72
+ const frequencies: [string, number][] = []
73
+ for (let i = 0; i < letters.length; i++) {
74
+ frequencies.push([letters[i], i + 1])
75
+ }
76
+ const segment = (letters.length * (letters.length + 1)) / 2
77
+ f = pickMe(frequencies, rng)
78
+ let counts2: Record<string, number> = {}
79
+ for (const l of letters) counts2[l] = 0
80
+ for (let i = 0, lim = segment * 1000; i < lim; i++) counts2[f()] += 1
81
+ for (const [l, f] of frequencies) {
82
+ const c = Number(counts2[l])
83
+ test(`we got something for ${l}`, () => expect(c).toBeGreaterThan(0))
84
+ const expectation = f * 1000
85
+ test(`we got roughly as many as we expected for ${l}, with frequency ${f}`, () =>
86
+ expect(Math.round(c / expectation)).toEqual(1))
87
+ }
88
+ const f1 = pickMe(
89
+ [
90
+ ['foo', 1],
91
+ ['bar', 1],
92
+ ['baz', 1],
93
+ ],
94
+ rando(1),
95
+ )
96
+ const f2 = pickMe(['foo', 'bar', 'baz'], rando(1))
97
+ const ar1: string[] = []
98
+ const ar2: string[] = []
99
+ for (let i = 0; i < 100; i++) {
100
+ ar1.push(f1())
101
+ ar2.push(f2())
102
+ }
103
+ test('frequencies are optional if all are the same', () => {
104
+ expect(ar1).toEqual(ar2)
105
+ })
106
+ })
package/src/index.ts ADDED
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Generates a zero-argument function that returns an item from the frequency list
3
+ * parameter with a probability concordant with its specified frequency.
4
+ *
5
+ * The required parameter is a list of pairs: an item to pick and its frequency. The "frequency"
6
+ * is simply a positive number which determines the probability of picking one item relative to another.
7
+ * If the parameters are `[[1, 1], [2, 2]]`, you will get twice as many 2s as 1s. You will get the same
8
+ * results with `[[1, 0.1], [2, 0.2]]`, `[[1, 10], [2, 20]]`, and `[[1, 0.13], [2, 0.26]]`.
9
+ *
10
+ * The second, optional parameter is a random number sequence generator. Provide this if you want a reproducible
11
+ * sequence of selections from your frequency list. If this doesn't concern you, leave it off and take
12
+ * whatever `Math.random()` gives you.
13
+ *
14
+ * If the frequency list is not a list of pairs but just a list of items, this is equivalent to a list of
15
+ * pairs where all the frequencies are the same. (Note, this will not work if the items are all pairs whose
16
+ * second value is a number. If you want to pick among such pairs you'll need to wrap them in new pairs.)
17
+ *
18
+ * An item with
19
+ * a non-positive frequency will be culled from the list. `pickMe` will throw an error if the list is empty.
20
+ * Likewise, it will throw an error if any item appears more than once in the list. `[]` is
21
+ * not good. `[[1, 1], [1, 2]]` is no better.
22
+ *
23
+ * Note, the item returned by `pickMe` is the item you provided, not a copy. If you are picking from a list of
24
+ * objects and you modify one of them, it will remain modified.
25
+ *
26
+ * Finally, `pickMe` compiles an efficient picker from the parameters provided. As with other compiled things, such
27
+ * as regular expressions, you want to do this one time in an initialization phase and then reuse it in loops.
28
+ * The compilation is not terribly expensive, but skipping it altogether is cheaper.
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * import { rando, pickMe } from 'pick-me'
33
+ *
34
+ * // make a random number generator with a seed of 1
35
+ * const rng = rando(1)
36
+ * const fooBarBaz = pickMe([["foo", 1], ["bar", 2], ["baz", 3]], rng)
37
+ * const ar: string[] = []
38
+ * for (let i = 0; i < 10; i++) ar.push(fooBarBaz())
39
+ * // => [ 'baz', 'foo', 'baz', 'baz', 'baz', 'bar', 'baz', 'baz', 'bar', 'baz' ]
40
+ * ```
41
+ *
42
+ * @param {[T, number][] | T[]} frequencies - phrases to match
43
+ * @param {() => number} [rando=() => Math.random()] - random number generator
44
+ * @returns {() => T} a picker of T's
45
+ */
46
+ export function pickMe<T>(frequencies: [T, number][] | T[], rando?: () => number): () => T {
47
+ frequencies = sanitize(normalize(frequencies))
48
+ // short-circuit edge cases
49
+ if (frequencies.length === 0) throw new Error(`nothing to select in ${frequencies}`)
50
+ if (frequencies.length === 1) {
51
+ const [t] = frequencies[0]
52
+ return () => t
53
+ }
54
+ // throw an error in case of duplicates
55
+ // it is difficult to do this efficiently because we allow T to be anything
56
+ for (let i = 0, lim = frequencies.length - 1; i < lim; i++) {
57
+ const t = frequencies[i][0]
58
+ for (let j = i + 1; j < frequencies.length; j++) {
59
+ if (t === frequencies[j][0]) throw new Error(`${t} appears more than once among frequencies`)
60
+ }
61
+ }
62
+ rando ??= () => Math.random()
63
+ let total = 0,
64
+ acc = 0
65
+ for (const [, n] of frequencies) total += n
66
+ for (let i = 0; i < frequencies.length; i++) {
67
+ const [, n] = frequencies[i]
68
+ acc += n
69
+ frequencies[i][1] = acc / total
70
+ }
71
+ const items: T[] = [],
72
+ thresholds: number[] = []
73
+ for (const [t, n] of frequencies) {
74
+ items.push(t)
75
+ thresholds.push(n)
76
+ }
77
+ const f = thresholder(thresholds)
78
+ return () => items[f(rando!())]!
79
+ }
80
+
81
+ // take in an array of ambiguous type and return a list of pairs, T and frequency
82
+ function normalize<T>(frequencies: [T, number][] | T[]): [T, number][] {
83
+ if (frequencies.length === 0) return frequencies as any as [T, number][]
84
+ if ((frequencies as any).every((s: any) => Array.isArray(s) && s.length === 2 && typeof s[1] === 'number'))
85
+ return frequencies as any as [T, number][]
86
+ const ar = frequencies.map((t) => [t, 1])
87
+ return ar as any as [T, number][]
88
+ }
89
+
90
+ // remove impossible frequencies
91
+ function sanitize<T>(frequencies: [T, number][]): [T, number][] {
92
+ return frequencies.map(([t, n]) => [t, Number(n)]).filter(([, n]) => Number.isFinite(n) && n > 0) as any as [
93
+ T,
94
+ number,
95
+ ][]
96
+ }
97
+
98
+ // make a function that converts a random number into an index, preserving the frequencies
99
+ // assuming the random number is from an even distribution in the interval [0, 1]
100
+ function thresholder(thresholds: number[]): (n: number) => number {
101
+ return eval(`(n) => ${portion(thresholds, 0, thresholds.length)}`)
102
+ }
103
+
104
+ // recursively convert the threshold list into nested ternary operators
105
+ // this allows us to find our index in O(log(n)) comparisons
106
+ function portion(thresholds: number[], start: number, end: number): string {
107
+ const n = end - start
108
+ if (n === 1) return start.toString()
109
+ const i = start + (n % 2 === 0 ? n / 2 - 1 : (n - 1) / 2)
110
+ return `(n > ${thresholds[i]} ? ${portion(thresholds, i + 1, end)} : ${portion(thresholds, start, i + 1)})`
111
+ }
112
+
113
+ /**
114
+ * Generates a random number sequence generator. This is a demonstration generator
115
+ * useful for testing and documentation. Any zero-argument function that returns
116
+ * numbers will suffice for `pickMe`.
117
+ *
118
+ * The implementation of `rando` is taken from https://stackoverflow.com/a/47593316/15060051.
119
+ * It is the Mulberry32 algorithm.
120
+ *
121
+ * @example
122
+ * ```ts
123
+ * import { rando } from 'pick-me'
124
+ *
125
+ * // make a random number generator with a seed of 1
126
+ * const rng = rando(1)
127
+ * const ar: number[] = []
128
+ * for (let i = 0; i < 3; i++) ar.push(rng())
129
+ * // => [ 0.6270739405881613, 0.002735721180215478, 0.5274470399599522 ]
130
+ * ```
131
+ *
132
+ * @param {number} seed - the seed for a random number sequence
133
+ * @returns {() => number} a generator of random numbers
134
+ */
135
+ export function rando(seed: number): () => number {
136
+ return () => {
137
+ let t = (seed += 0x6d2b79f5)
138
+ t = Math.imul(t ^ (t >>> 15), t | 1)
139
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
140
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
141
+ }
142
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,103 @@
1
+ {
2
+ "compilerOptions": {
3
+ /* Visit https://aka.ms/tsconfig.json to read more about this file */
4
+
5
+ /* Projects */
6
+ // "incremental": true, /* Enable incremental compilation */
7
+ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8
+ // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
9
+ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
10
+ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11
+ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
+
13
+ /* Language and Environment */
14
+ "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15
+ // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
+ // "jsx": "preserve", /* Specify what JSX code is generated. */
17
+ // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
18
+ // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19
+ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
20
+ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21
+ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
22
+ // "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
23
+ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24
+ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25
+
26
+ /* Modules */
27
+ "module": "commonjs", /* Specify what module code is generated. */
28
+ // "rootDir": "./", /* Specify the root folder within your source files. */
29
+ // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
30
+ // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
31
+ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
32
+ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
33
+ // "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */
34
+ // "types": [], /* Specify type package names to be included without being referenced in a source file. */
35
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
36
+ // "resolveJsonModule": true, /* Enable importing .json files */
37
+ // "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
38
+
39
+ /* JavaScript Support */
40
+ // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
41
+ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
42
+ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
43
+
44
+ /* Emit */
45
+ "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
46
+ // "declarationMap": true, /* Create sourcemaps for d.ts files. */
47
+ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
48
+ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
49
+ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
50
+ "outDir": "./lib", /* Specify an output folder for all emitted files. */
51
+ // "removeComments": true, /* Disable emitting comments. */
52
+ // "noEmit": true, /* Disable emitting files from a compilation. */
53
+ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
54
+ // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
55
+ // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
56
+ // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
57
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
58
+ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
59
+ // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
60
+ // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
61
+ // "newLine": "crlf", /* Set the newline character for emitting files. */
62
+ // "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
63
+ // "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
64
+ // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
65
+ // "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
66
+ // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
67
+ // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
68
+
69
+ /* Interop Constraints */
70
+ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
71
+ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
72
+ "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
73
+ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
74
+ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
75
+
76
+ /* Type Checking */
77
+ "strict": true, /* Enable all strict type-checking options. */
78
+ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
79
+ // "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
80
+ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
81
+ // "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
82
+ // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
83
+ // "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
84
+ // "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
85
+ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
86
+ // "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
87
+ // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */
88
+ // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
89
+ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
90
+ // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
91
+ // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
92
+ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
93
+ // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
94
+ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
95
+ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
96
+
97
+ /* Completeness */
98
+ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
99
+ "skipLibCheck": true /* Skip type checking all .d.ts files. */
100
+ },
101
+ "include": ["src"],
102
+ "exclude": ["node_modules", "**/__tests__/*"]
103
+ }