-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
571 lines (520 loc) · 13.8 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
/**
* @overview A library of useful functions
* @author Gordon Larrigan
*/
/**
* Memoize a function
* @param {Function} f The function to memoize
* @returns {Function} A memoized version of the function
*/
const memoize = f => {
var cache = {};
return function(...args) {
return cache[args] ?? (cache[args] = f.apply(this, args));
};
};
/**
* Check if two numbers are approximately equal
* @param {number} a Number a
* @param {number} b Number b
* @param {number} [p=Number.EPSILON] The precision value
* @return {boolean} True if numbers a and b are approximately equal
*/
const floatEquals = (a, b, p = Number.EPSILON) => Math.abs(a - b) < p;
/**
* Clamp a number between min and max
* @param {number} a The number to clamp
* @param {number} [min=0] The minimum value
* @param {number} [max=1] The maximum value
* @return {number} A clamped number
*/
const clamp = (a, min = 0, max = 1) => a < min ? min : (a > max ? max : a);
/**
* Get the fractional part of a number
* @param {number} a The number from which to get the fractional part
* @return {number} The fractional part of the number
*/
const frac = a => a >= 0 ? a - Math.floor(a) : a - Math.ceil(a);
/**
* Round n to d decimal places
* @param {number} n The number to round
* @param {number} [d=0] The number of decimal places to round to
* @return {number} A rounded number
*/
const round = (n, d = 0) => {
const p = Math.pow(10, d);
return Math.round(n * p + Number.EPSILON) / p;
}
/**
* Do a linear interpolation between a and b
* @param {number} a The minimum number
* @param {number} b The maximum number
* @param {number} i The interpolation value, should be in the interval [0, 1]
* @return {number} An interpolated value in the interval [a, b]
*/
const lerp = (a, b, i) => a + (b - a) * i;
/**
* Get the position of i between a and b
* @param {number} a The minimum number
* @param {number} b The maximum number
* @param {number} i The interpolated value in the interval [a, b]
* @return {number} The position of i between a and b
*/
const unlerp = (a, b, i) => (i - a) / (b - a);
/**
* Do a bilinear interpolation
* @param {number} c00 Top-left value
* @param {number} c10 Top-right value
* @param {number} c01 Bottom-left value
* @param {number} c11 Bottom-right value
* @param {number} ix Interpolation value along x
* @param {number} iy Interpolation value along y
* @return {number} A bilinear interpolated value
*/
const blerp = (c00, c10, c01, c11, ix, iy) => lerp(lerp(c00, c10, ix), lerp(c01, c11, ix), iy);
/**
* Re-map a number i from range a1...a2 to b1...b2
* @param {number} i The number to re-map
* @param {number} a1
* @param {number} a2
* @param {number} b1
* @param {number} b2
* @return {number}
*/
const remap = (i, a1, a2, b1, b2) => b1 + (i - a1) * (b2 - b1) / (a2 - a1);
/**
* Do a smooth interpolation between a and b
* @param {number} a The minimum number
* @param {number} b The maximum number
* @param {number} i The interpolation value
* @return {number} An interpolated value in the interval [a, b]
*/
const smoothstep = (a, b, i) => lerp(a, b, 3 * Math.pow(i, 2) - 2 * Math.pow(i, 3));
/**
* Get an angle in radians
* @param {number} degrees The angle in degrees
* @return {number} The angle in radians
*/
const radians = degrees => (Math.PI / 180) * degrees;
/**
* Get an angle in degrees
* @param {number} radians The angle in radians
* @return {number} The angle in degrees
*/
const degrees = radians => (180 / Math.PI) * radians;
/**
* Get a random float in the interval [min, max)
* @param {number} min Inclusive min
* @param {number} max Exclusive max
* @return {number} A random float in the interval [min, max)
*/
const randomBetween = (min, max) => Math.random() * (max - min) + min;
/**
* Get a random integer in the interval [min, max]
* @param {number} min Inclusive min
* @param {number} max Inclusive max
* @return {number} A random integer in the interval [min, max]
*/
const randomIntBetween = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
/**
* Get a normally-distributed random number
* @param {number} [mu=0.5] The mean value
* @param {number} [sigma=0.5] The standard deviation
* @param {number} [samples=2] The number of samples
* @return {number} A normally-distributed random number
*/
const cltRandom = (mu = 0.5, sigma = 0.5, samples = 2) => {
let total = 0;
for (let i = samples; i--;) {
total += Math.random();
}
return mu + (total - samples / 2) / (samples / 2) * sigma;
};
/**
* Get a normally-distributed random integer in the interval [min, max]
* @param {number} min Inclusive min
* @param {number} max Inclusive max
* @return {number} A normally-distributed random integer
*/
const cltRandomInt = (min, max) => Math.floor(min + cltRandom(0.5, 0.5, 2) * (max + 1 - min));
/**
* Return a weighted random integer
* @param {Array<number>} w An array of weights
* @return {number} An index from w
*/
const weightedRandom = w => {
let total = w.reduce((a, i) => a + i, 0), n = 0;
const r = Math.random() * total;
while (total > r) {
total -= w[n++];
}
return n - 1;
};
/**
* An interpolation function
* @callback InterpolationFunction
* @param {number} a The minimum number
* @param {number} b The maximum number
* @param {number} i The interpolation value, should be in the interval [0, 1]
* @return {number} The interpolated value in the interval [a, b]
*/
/**
* Return an interpolated value from an array
* @param {Array<number>} a An array of values interpolate
* @param {number} i A number in the interval [0, 1]
* @param {InterpolationFunction} [f=Math.lerp] The interpolation function to use
* @return {number} An interpolated value in the interval [min(a), max(a)]
*/
const lerpArray = (a, i, f = lerp) => {
const s = i * (a.length - 1);
const p = clamp(Math.trunc(s), 0, a.length - 1);
return f(a[p] || 0, a[p + 1] || 0, frac(s));
};
/**
* Get the dot product of two vectors
* @param {Array<number>} a Vector a
* @param {Array<number>} b Vector b
* @return {number} a ∙ b
*/
const dot = (a, b) => a.reduce((n, v, i) => n + v * b[i], 0);
/**
* Get the factorial of a number
* @param {number} a
* @return {number} a!
*/
const factorial = a => {
let result = 1;
for (let i = 2; i <= a; i++) {
result *= i;
}
return result;
};
/**
* Get the number of permutations of r elements from a set of n elements
* @param {number} n
* @param {number} r
* @return {number} nPr
*/
const npr = (n, r) => factorial(n) / factorial(n - r);
/**
* Get the number of combinations of r elements from a set of n elements
* @param {number} n
* @param {number} r
* @return {number} nCr
*/
const ncr = (n, r) => factorial(n) / (factorial(r) * factorial(n - r));
/**
* Generate all permutations of r elements from an array
*
* @example
* ```js
* permutations([1, 2, 3], 2);
* ```
*
* Output:
* ```json
* [
* [1, 2],
* [1, 3],
* [2, 1],
* [2, 3],
* [3, 1],
* [3, 2]
* ]
* ```
* @param {Array<*>} a
* @param {number} r The number of elements to choose in each permutation
* @return {Array<Array<*>>} An array of permutation arrays
*/
const permutations = (a, r) => {
if (r === 1) {
return a.map(item => [item]);
}
return a.reduce(
(acc, item, i) => [
...acc,
...permutations(a.slice(0, i).concat(a.slice(i + 1)), r - 1).map(c => [item, ...c]),
],
[]
);
}
/**
* Generate all combinations of r elements from an array
*
* @example
* ```js
* combinations([1, 2, 3], 2);
* ```
*
* Output:
* ```json
* [
* [1, 2],
* [1, 3],
* [2, 3]
* ]
* ```
* @param {Array<*>} a
* @param {number} r The number of elements to choose in each combination
* @return {Array<Array<*>>} An array of combination arrays
*/
const combinations = (a, r) => {
if (r === 1) {
return a.map(item => [item]);
}
return a.reduce(
(acc, item, i) => [
...acc,
...combinations(a.slice(i + 1), r - 1).map(c => [item, ...c]),
],
[]
);
};
/**
* Get a cartesian product of arrays
*
* @example
* ```js
* cartesian([1, 2, 3], ['a', 'b']);
* ```
*
* Output:
* ```json
* [
* [1, "a"],
* [1, "b"],
* [2, "a"],
* [2, "b"],
* [3, "a"],
* [3, "b"]
* ]
* ```
*/
const cartesian = (...arr) =>
arr.reduce(
(a, b) => a.flatMap(c => b.map(d => [...c, d])),
[[]]
);
/**
* A function for generating array values
* @callback TimesFunction
* @param {number} i The array index
* @return {*} The array value
*/
/**
* Return a new array with length n by calling function f(i) on each element
* @param {TimesFunction} f
* @param {number} n The size of the array
* @return {Array<*>}
*/
const times = (f, n) => Array(n).fill(0).map((_, i) => f(i));
/**
* Return an array containing numbers 0->(n - 1)
* @param {number} n The size of the array
* @return {Array<number>} An array of integers 0->(n - 1)
*/
const range = n => times(i => i, n);
/**
* Zip multiple arrays together, i.e. ([1, 2, 3], [a, b, c]) => [[1, a], [2, b], [3, c]]
* @param {...Array<*>} a The arrays to zip
* @return {Array<Array<*>>}
*/
const zip = (...a) => times(i => a.map(a => a[i]), Math.max(...a.map(a => a.length)));
/**
* Return array[i] with positive and negative wrapping
* @param {Array<*>} a The array to access
* @param {number} i The positively/negatively wrapped array index
* @return {*} An element from the array
*/
const at = (a, i) => a[i < 0 ? a.length - (Math.abs(i + 1) % a.length) - 1 : i % a.length];
/**
* Return the last element of an array without removing it
* @param {Array<*>} a
* @return {*} The last element from the array
*/
const peek = (a) => {
if (!a.length) {
return undefined;
}
return a[a.length - 1];
};
/**
* Return the index for a given position in an unrolled 2d array
* @param {number} x The x position
* @param {number} y The y position
* @param {number} w The width of the 2d array
* @returns {number} The index in the unrolled array
*/
const ind = (x, y, w) => x + y * w;
/**
* Return the position for a given index in an unrolled 2d array
* @param {number} i The index
* @param {number} w The width of the 2d array
* @returns {Array<number>} The position as a 2-tuple
*/
const pos = (i, w) => [i % w, Math.floor(i / w)];
/**
* Chop an array into chunks of size n
* @param {Array<*>} a
* @param {number} n The chunk size
* @return {Array<Array<*>>} An array of array chunks
*/
const chunk = (a, n) => times(i => a.slice(i * n, i * n + n), Math.ceil(a.length / n));
/**
* Randomly shuffle a shallow copy of an array
* @param {Array<*>} a
* @return {Array<*>} The shuffled array
*/
const shuffle = a => a.slice().sort(() => Math.random() - 0.5);
/**
* Flatten an object
* @param {object} o
* @param {string} concatenator The string to use for concatenating keys
* @return {object} A flattened object
*/
const flat = (o, concatenator = '.') => {
return Object.keys(o).reduce((acc, key) => {
if (o[key] instanceof Date) {
return {
...acc,
[key]: o[key].toISOString(),
};
}
if (typeof o[key] !== 'object' || !o[key]) {
return {
...acc,
[key]: o[key],
};
}
const flattened = flat(o[key], concatenator);
return {
...acc,
...Object.keys(flattened).reduce(
(childAcc, childKey) => ({
...childAcc,
[`${key}${concatenator}${childKey}`]: flattened[childKey],
}),
{}
),
};
}, {});
};
/**
* Unflatten an object
* @param {object} o
* @param {string} concatenator The string to check for in concatenated keys
* @return {object} An un-flattened object
*/
const unflat = (o, concatenator = '.') => {
let result = {}, temp, substrings, property, i;
for (property in o) {
substrings = property.split(concatenator);
temp = result;
for (i = 0; i < substrings.length - 1; i++) {
if (!(substrings[i] in temp)) {
if (isFinite(substrings[i + 1])) {
temp[substrings[i]] = [];
} else {
temp[substrings[i]] = {};
}
}
temp = temp[substrings[i]];
}
temp[substrings[substrings.length - 1]] = o[property];
}
return result;
};
/**
* A split predicate
* @callback SplitPredicate
* @param {any} value The current value
* @return {boolean} True if the array should split at this index
*/
/**
* Split an array into sub-arrays based on a predicate
* @param {Array<*>} array
* @param {SplitPredicate} predicate
* @return {Array<Array<*>>} An array of arrays
*/
const split = (array, predicate) => {
const result = [];
let current = [];
for (const value of array) {
if (predicate(value)) {
if (current.length) {
result.push(current);
}
current = [value];
} else {
current.push(value);
}
}
result.push(current);
return result;
};
/**
* Pluck keys from an object
* @param {object} o
* @param {...string} keys The keys to pluck from the object
* @return {object} An object containing the plucked keys
*/
const pluck = (o, ...keys) => {
return keys.reduce(
(result, key) => Object.assign(result, { [key]: o[key] }),
{}
);
};
/**
* Exclude keys from an object
* @param {object} o
* @param {...string} keys The keys to exclude from the object
* @return {object} An object containing all keys except excluded keys
*/
const exclude = (o, ...keys) => {
return Object.fromEntries(
Object.entries(o).filter(([key]) => !keys.includes(key))
);
};
if (typeof module !== 'undefined') {
module.exports = {
memoize,
floatEquals,
clamp,
frac,
round,
lerp,
unlerp,
blerp,
remap,
smoothstep,
radians,
degrees,
randomBetween,
randomIntBetween,
cltRandom,
cltRandomInt,
weightedRandom,
lerpArray,
dot,
factorial,
npr,
ncr,
permutations,
combinations,
cartesian,
times,
range,
zip,
at,
peek,
ind,
pos,
chunk,
shuffle,
flat,
unflat,
split,
pluck,
exclude,
};
}