@asd14/m 9.0.0 → 10.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/dist/src/debounce/debounce.d.ts +13 -1
- package/dist/src/debounce/debounce.js +27 -20
- package/dist/src/distinct/by/distinct-by.d.ts +3 -0
- package/dist/src/distinct/by/distinct-by.js +3 -0
- package/dist/src/distinct/distinct.js +12 -3
- package/dist/src/drop/drop.d.ts +38 -0
- package/dist/src/drop/drop.js +56 -0
- package/dist/src/escape/escape.js +6 -1
- package/dist/src/escape/reg-exp/escape-reg-exp.d.ts +3 -2
- package/dist/src/escape/reg-exp/escape-reg-exp.js +11 -4
- package/dist/src/flatten/flatten.d.ts +7 -0
- package/dist/src/flatten/flatten.js +14 -1
- package/dist/src/fuzzy-match/fuzzy-match.d.ts +3 -0
- package/dist/src/fuzzy-match/fuzzy-match.js +91 -55
- package/dist/src/group/group-by.d.ts +19 -7
- package/dist/src/group/group-by.js +20 -2
- package/dist/src/index-by/index-by.d.ts +70 -0
- package/dist/src/index-by/index-by.js +82 -0
- package/dist/src/index.d.ts +12 -1
- package/dist/src/index.js +12 -9
- package/dist/src/intersect/by/intersect-by.d.ts +48 -0
- package/dist/src/intersect/by/intersect-by.js +75 -0
- package/dist/src/intersect/intersect.d.ts +42 -0
- package/dist/src/intersect/intersect.js +63 -0
- package/dist/src/is-deep-equal/is-deep-equal.d.ts +20 -5
- package/dist/src/is-deep-equal/is-deep-equal.js +44 -7
- package/dist/src/is-uri/is-uri.js +12 -9
- package/dist/src/max/by/max-by.d.ts +52 -0
- package/dist/src/max/by/max-by.js +69 -0
- package/dist/src/max/max.d.ts +34 -0
- package/dist/src/max/max.js +49 -0
- package/dist/src/merge/merge.d.ts +5 -1
- package/dist/src/merge/merge.js +12 -6
- package/dist/src/min/by/min-by.d.ts +52 -0
- package/dist/src/min/by/min-by.js +69 -0
- package/dist/src/min/min.d.ts +34 -0
- package/dist/src/min/min.js +49 -0
- package/dist/src/pick/pick.js +7 -0
- package/dist/src/read/read.d.ts +1 -0
- package/dist/src/read/read.js +1 -0
- package/dist/src/take/last/take-last.d.ts +38 -0
- package/dist/src/take/last/take-last.js +56 -0
- package/dist/src/take/take.d.ts +38 -0
- package/dist/src/take/take.js +56 -0
- package/dist/src/throttle/throttle.d.ts +11 -1
- package/dist/src/throttle/throttle.js +49 -43
- package/dist/src/unite/by/unite-by.d.ts +3 -0
- package/dist/src/unite/by/unite-by.js +3 -0
- package/dist/src/update/update.d.ts +2 -2
- package/dist/src/utils/build-patch.js +3 -1
- package/dist/src/utils/parse-timer-options.d.ts +22 -0
- package/dist/src/utils/parse-timer-options.js +44 -0
- package/dist/src/utils/set-own.d.ts +5 -4
- package/dist/src/utils/set-own.js +6 -5
- package/dist/src/values/values.d.ts +42 -0
- package/dist/src/values/values.js +46 -0
- package/dist/src/write/write.d.ts +53 -0
- package/dist/src/write/write.js +104 -0
- package/dist/src/zip-to-object/zip-to-object.js +7 -0
- package/dist/types/object.d.ts +53 -4
- package/docs/SPEC.md +8 -7
- package/docs/how-to/prototype-pollution-tests.md +156 -0
- package/docs/how-to/tape-runtime-tests.md +30 -21
- package/docs/how-to/tstyche-type-tests.md +29 -14
- package/package.json +8 -5
- package/dist/src/evolve/deep-by/evolve-deep-by.d.ts +0 -65
- package/dist/src/evolve/deep-by/evolve-deep-by.js +0 -90
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
type DebounceOptions = {
|
|
2
|
-
/** Milliseconds to wait after the last call, default `50` */
|
|
2
|
+
/** Milliseconds to wait after the last call, at most 2,147,483,647, default `50` */
|
|
3
3
|
wait?: number;
|
|
4
|
+
/** Drops the pending call when aborted, and makes later calls do nothing */
|
|
5
|
+
signal?: AbortSignal;
|
|
4
6
|
};
|
|
5
7
|
type DebounceFn = {
|
|
6
8
|
<P extends unknown[]>(options: DebounceOptions, fn: (...params: P) => unknown): (...params: P) => void;
|
|
@@ -29,6 +31,16 @@ type DebounceFn = {
|
|
|
29
31
|
* save(draft)
|
|
30
32
|
* // 100 ms later: saveDraft(draft) runs
|
|
31
33
|
*
|
|
34
|
+
* // Abort with a signal, eg. when a React component unmounts: the pending
|
|
35
|
+
* // call never runs, and later calls do nothing
|
|
36
|
+
* useEffect(() => {
|
|
37
|
+
* const controller = new AbortController()
|
|
38
|
+
* const save = debounce({ wait: 300, signal: controller.signal }, saveDraft)
|
|
39
|
+
*
|
|
40
|
+
* editor.on("change", save)
|
|
41
|
+
* return () => controller.abort()
|
|
42
|
+
* }, [])
|
|
43
|
+
*
|
|
32
44
|
* @name debounce
|
|
33
45
|
* @tag Function
|
|
34
46
|
*
|
|
@@ -1,10 +1,21 @@
|
|
|
1
|
-
import { isPlainObject } from "../is/is.js";
|
|
2
1
|
import { type } from "../type/type.js";
|
|
3
|
-
|
|
2
|
+
import { _parseTimerOptions } from "../utils/parse-timer-options.js";
|
|
3
|
+
const _debounce = (fn, wait, signal)=>{
|
|
4
4
|
let timer;
|
|
5
|
+
signal?.addEventListener("abort", ()=>{
|
|
6
|
+
clearTimeout(timer);
|
|
7
|
+
timer = undefined;
|
|
8
|
+
}, {
|
|
9
|
+
once: true
|
|
10
|
+
});
|
|
5
11
|
return (...params)=>{
|
|
12
|
+
if (signal?.aborted) {
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
6
15
|
clearTimeout(timer);
|
|
7
16
|
timer = setTimeout(()=>{
|
|
17
|
+
// Let go of the timer, and with it of `params`, once fn runs
|
|
18
|
+
timer = undefined;
|
|
8
19
|
fn(...params);
|
|
9
20
|
}, wait);
|
|
10
21
|
};
|
|
@@ -32,32 +43,28 @@ const _debounce = (fn, wait)=>{
|
|
|
32
43
|
* save(draft)
|
|
33
44
|
* // 100 ms later: saveDraft(draft) runs
|
|
34
45
|
*
|
|
46
|
+
* // Abort with a signal, eg. when a React component unmounts: the pending
|
|
47
|
+
* // call never runs, and later calls do nothing
|
|
48
|
+
* useEffect(() => {
|
|
49
|
+
* const controller = new AbortController()
|
|
50
|
+
* const save = debounce({ wait: 300, signal: controller.signal }, saveDraft)
|
|
51
|
+
*
|
|
52
|
+
* editor.on("change", save)
|
|
53
|
+
* return () => controller.abort()
|
|
54
|
+
* }, [])
|
|
55
|
+
*
|
|
35
56
|
* @name debounce
|
|
36
57
|
* @tag Function
|
|
37
58
|
*
|
|
38
59
|
* @see {@link throttle}
|
|
39
60
|
*/ const debounce = (...params)=>{
|
|
40
61
|
const fn = params[params.length - 1];
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
if (!isPlainObject(options)) {
|
|
45
|
-
throw new TypeError(`@asd14/m/debounce: expected 'options' to be 'Object', got '${type(options)}'`);
|
|
46
|
-
}
|
|
47
|
-
const optionWait = options["wait"];
|
|
48
|
-
if (optionWait !== undefined) {
|
|
49
|
-
if (typeof optionWait !== "number") {
|
|
50
|
-
throw new TypeError(`@asd14/m/debounce: expected 'wait' to be 'Number', got '${type(optionWait)}'`);
|
|
51
|
-
}
|
|
52
|
-
if (!(optionWait >= 0)) {
|
|
53
|
-
throw new TypeError(`@asd14/m/debounce: expected 'wait' to be 'NonNegative', got '${String(optionWait)}'`);
|
|
54
|
-
}
|
|
55
|
-
wait = optionWait;
|
|
56
|
-
}
|
|
57
|
-
}
|
|
62
|
+
const { wait, signal } = _parseTimerOptions(params.length > 1 ? params[0] : undefined, {
|
|
63
|
+
fnName: "debounce"
|
|
64
|
+
});
|
|
58
65
|
if (typeof fn !== "function") {
|
|
59
66
|
throw new TypeError(`@asd14/m/debounce: expected 'fn' to be 'Function', got '${type(fn)}'`);
|
|
60
67
|
}
|
|
61
|
-
return _debounce(fn, wait);
|
|
68
|
+
return _debounce(fn, wait, signal);
|
|
62
69
|
};
|
|
63
70
|
export { debounce };
|
|
@@ -7,6 +7,9 @@ type DistinctByFn = {
|
|
|
7
7
|
* Remove duplicate values from an array using a custom equality function.
|
|
8
8
|
* Order is preserved - first occurrence wins.
|
|
9
9
|
*
|
|
10
|
+
* Compares each item with each kept item, so the time grows with the square
|
|
11
|
+
* of the input. To compare with SameValueZero, use `distinct`, which is linear.
|
|
12
|
+
*
|
|
10
13
|
* Input is never mutated - always returns a new array.
|
|
11
14
|
*
|
|
12
15
|
* @param {Function} fn - Equality function `(newItem, keptItem) => boolean`,
|
|
@@ -23,6 +23,9 @@ const _distinctBy = (fn, input)=>{
|
|
|
23
23
|
* Remove duplicate values from an array using a custom equality function.
|
|
24
24
|
* Order is preserved - first occurrence wins.
|
|
25
25
|
*
|
|
26
|
+
* Compares each item with each kept item, so the time grows with the square
|
|
27
|
+
* of the input. To compare with SameValueZero, use `distinct`, which is linear.
|
|
28
|
+
*
|
|
26
29
|
* Input is never mutated - always returns a new array.
|
|
27
30
|
*
|
|
28
31
|
* @param {Function} fn - Equality function `(newItem, keptItem) => boolean`,
|
|
@@ -1,6 +1,4 @@
|
|
|
1
|
-
import { isEqual } from "../is-equal/is-equal.js";
|
|
2
1
|
import { type } from "../type/type.js";
|
|
3
|
-
import { distinctBy } from "./by/distinct-by.js";
|
|
4
2
|
/**
|
|
5
3
|
* Remove duplicate values from an array. Compares with SameValueZero, as
|
|
6
4
|
* `Array.prototype.includes`: `NaN` equals `NaN`. Order is preserved - first
|
|
@@ -34,6 +32,17 @@ import { distinctBy } from "./by/distinct-by.js";
|
|
|
34
32
|
if (!Array.isArray(input)) {
|
|
35
33
|
throw new TypeError(`@asd14/m/distinct: expected 'input' to be 'Array', got '${type(input)}'`);
|
|
36
34
|
}
|
|
37
|
-
|
|
35
|
+
// A Set compares with SameValueZero, as isEqual does, so one pass does it.
|
|
36
|
+
// distinctBy compares each item with each kept one, for its own equality
|
|
37
|
+
const seen = new Set();
|
|
38
|
+
const result = [];
|
|
39
|
+
for(let index = 0, length = input.length; index < length; index++){
|
|
40
|
+
const item = input[index];
|
|
41
|
+
if (!seen.has(item)) {
|
|
42
|
+
seen.add(item);
|
|
43
|
+
result.push(item);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return result;
|
|
38
47
|
};
|
|
39
48
|
export { distinct };
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
type DropFn = {
|
|
2
|
+
<T>(count: number, input: readonly T[]): T[];
|
|
3
|
+
(count: number): <T>(input: readonly T[]) => T[];
|
|
4
|
+
<T>(input: readonly T[]): T[];
|
|
5
|
+
};
|
|
6
|
+
/**
|
|
7
|
+
* Remove elements from the start of an array. When called with only an array,
|
|
8
|
+
* removes the first element (count defaults to 1).
|
|
9
|
+
*
|
|
10
|
+
* Input is never mutated - always returns a new array.
|
|
11
|
+
*
|
|
12
|
+
* @param {number} count - Number of elements, a non-negative integer
|
|
13
|
+
* @param {Array} input - Source array
|
|
14
|
+
*
|
|
15
|
+
* @returns {Array} New array with elements removed from the start
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* drop([1, 2, 3])
|
|
19
|
+
* // => [2, 3]
|
|
20
|
+
*
|
|
21
|
+
* drop(2, [1, 2, 3])
|
|
22
|
+
* // => [3]
|
|
23
|
+
*
|
|
24
|
+
* drop(2)([1, 2, 3])
|
|
25
|
+
* // => [3]
|
|
26
|
+
*
|
|
27
|
+
* pipe(drop(1), map(read("id")))([{ id: 1 }, { id: 2 }, { id: 3 }])
|
|
28
|
+
* // => [2, 3]
|
|
29
|
+
*
|
|
30
|
+
* @name drop
|
|
31
|
+
* @tag Array
|
|
32
|
+
*
|
|
33
|
+
* @see {@link dropLast}
|
|
34
|
+
* @see {@link take}
|
|
35
|
+
*/
|
|
36
|
+
declare const drop: DropFn;
|
|
37
|
+
export { drop };
|
|
38
|
+
export type { DropFn };
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { type } from "../type/type.js";
|
|
2
|
+
const _drop = (count, input)=>{
|
|
3
|
+
if (!Array.isArray(input)) {
|
|
4
|
+
throw new TypeError(`@asd14/m/drop: expected 'input' to be 'Array', got '${type(input)}'`);
|
|
5
|
+
}
|
|
6
|
+
return count >= input.length ? [] : input.slice(count);
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* Remove elements from the start of an array. When called with only an array,
|
|
10
|
+
* removes the first element (count defaults to 1).
|
|
11
|
+
*
|
|
12
|
+
* Input is never mutated - always returns a new array.
|
|
13
|
+
*
|
|
14
|
+
* @param {number} count - Number of elements, a non-negative integer
|
|
15
|
+
* @param {Array} input - Source array
|
|
16
|
+
*
|
|
17
|
+
* @returns {Array} New array with elements removed from the start
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* drop([1, 2, 3])
|
|
21
|
+
* // => [2, 3]
|
|
22
|
+
*
|
|
23
|
+
* drop(2, [1, 2, 3])
|
|
24
|
+
* // => [3]
|
|
25
|
+
*
|
|
26
|
+
* drop(2)([1, 2, 3])
|
|
27
|
+
* // => [3]
|
|
28
|
+
*
|
|
29
|
+
* pipe(drop(1), map(read("id")))([{ id: 1 }, { id: 2 }, { id: 3 }])
|
|
30
|
+
* // => [2, 3]
|
|
31
|
+
*
|
|
32
|
+
* @name drop
|
|
33
|
+
* @tag Array
|
|
34
|
+
*
|
|
35
|
+
* @see {@link dropLast}
|
|
36
|
+
* @see {@link take}
|
|
37
|
+
*/ const drop = (...params)=>{
|
|
38
|
+
// @signature (input)
|
|
39
|
+
if (Array.isArray(params[0])) {
|
|
40
|
+
return _drop(1, params[0]);
|
|
41
|
+
}
|
|
42
|
+
const count = params[0];
|
|
43
|
+
if (typeof count !== "number") {
|
|
44
|
+
throw new TypeError(`@asd14/m/drop: expected 'count' to be 'Number', got '${type(count)}'`);
|
|
45
|
+
}
|
|
46
|
+
if (!Number.isInteger(count) || count < 0) {
|
|
47
|
+
throw new TypeError(`@asd14/m/drop: expected 'count' to be 'NonNegativeInteger', got '${String(count)}'`);
|
|
48
|
+
}
|
|
49
|
+
// @signature (count, input)
|
|
50
|
+
if (params.length === 2) {
|
|
51
|
+
return _drop(count, params[1]);
|
|
52
|
+
}
|
|
53
|
+
// @signature (count) => (input)
|
|
54
|
+
return (input)=>_drop(count, input);
|
|
55
|
+
};
|
|
56
|
+
export { drop };
|
|
@@ -3,7 +3,12 @@ const _escape = (match, input)=>{
|
|
|
3
3
|
if (typeof input !== "string") {
|
|
4
4
|
throw new TypeError(`@asd14/m/escape: expected 'input' to be 'String', got '${type(input)}'`);
|
|
5
5
|
}
|
|
6
|
-
|
|
6
|
+
// A sticky (y) regex matches from its lastIndex, and replace leaves that
|
|
7
|
+
// where the last match ended. A copy starts each call at 0, and keeps the
|
|
8
|
+
// caller's regex as it was. A g regex is reset by replace, and a regex with
|
|
9
|
+
// neither flag ignores lastIndex, so both are used as they are
|
|
10
|
+
const pattern = match instanceof RegExp && match.sticky ? new RegExp(match) : match;
|
|
11
|
+
return input.replace(pattern, "\\$&");
|
|
7
12
|
};
|
|
8
13
|
/**
|
|
9
14
|
* Escape characters matched by a regular expression or a string in a string
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
type EscapeRegExpFn = (input: string) => string;
|
|
2
2
|
/**
|
|
3
3
|
* Escape regular expression special characters in a string so it can be
|
|
4
|
-
* safely used inside a `RegExp` constructor
|
|
5
|
-
*
|
|
4
|
+
* safely used inside a `RegExp` constructor: in a character class or outside
|
|
5
|
+
* one, with no flag, the `u` flag or the `v` flag. The characters the `v` flag
|
|
6
|
+
* reserves, eg. `&` and `,`, come back as `\xNN`.
|
|
6
7
|
*
|
|
7
8
|
* Input is never mutated - always returns a new string.
|
|
8
9
|
*
|
|
@@ -1,9 +1,16 @@
|
|
|
1
1
|
import { type } from "../../type/type.js";
|
|
2
|
-
const REG_EXP_SPECIAL = /[$()
|
|
2
|
+
const REG_EXP_SPECIAL = /[$()*+.?[\\\]^{|}]/g;
|
|
3
|
+
// With the `v` flag, a doubled one of these is an operator inside a character
|
|
4
|
+
// class, eg. `&&`, and `\-` is valid only inside one. A backslash escape of
|
|
5
|
+
// them is invalid outside a class with `u`, so they get `\xNN`, which is valid
|
|
6
|
+
// in every mode
|
|
7
|
+
const V_FLAG_RESERVED = /[!#%&,\-/:;<=>@`~]/g;
|
|
8
|
+
const _toHex = (char)=>`\\x${char.charCodeAt(0).toString(16).padStart(2, "0")}`;
|
|
3
9
|
/**
|
|
4
10
|
* Escape regular expression special characters in a string so it can be
|
|
5
|
-
* safely used inside a `RegExp` constructor
|
|
6
|
-
*
|
|
11
|
+
* safely used inside a `RegExp` constructor: in a character class or outside
|
|
12
|
+
* one, with no flag, the `u` flag or the `v` flag. The characters the `v` flag
|
|
13
|
+
* reserves, eg. `&` and `,`, come back as `\xNN`.
|
|
7
14
|
*
|
|
8
15
|
* Input is never mutated - always returns a new string.
|
|
9
16
|
*
|
|
@@ -29,6 +36,6 @@ const REG_EXP_SPECIAL = /[$()*+\-.?[\\\]^{|}]/g;
|
|
|
29
36
|
if (typeof input !== "string") {
|
|
30
37
|
throw new TypeError(`@asd14/m/escapeRegExp: expected 'input' to be 'String', got '${type(input)}'`);
|
|
31
38
|
}
|
|
32
|
-
return input.replace(REG_EXP_SPECIAL, "\\$&");
|
|
39
|
+
return input.replace(REG_EXP_SPECIAL, "\\$&").replace(V_FLAG_RESERVED, _toHex);
|
|
33
40
|
};
|
|
34
41
|
export { escapeRegExp };
|
|
@@ -18,6 +18,10 @@ type FlattenFn = {
|
|
|
18
18
|
* For arrays, concatenates all nested arrays into a single flat array.
|
|
19
19
|
* For objects, joins nested keys with a separator into a flat structure.
|
|
20
20
|
*
|
|
21
|
+
* It recurses, so the stack limits the depth: an object nested a few thousand
|
|
22
|
+
* levels deep throws a `RangeError`. `JSON.parse` accepts any depth, so check
|
|
23
|
+
* the depth of untrusted input first, if it can be that deep.
|
|
24
|
+
*
|
|
21
25
|
* Input is never mutated - always returns a new array or object.
|
|
22
26
|
*
|
|
23
27
|
* Only a plain object is flattened. An empty object, a `Date`, a `Map` and a
|
|
@@ -32,6 +36,9 @@ type FlattenFn = {
|
|
|
32
36
|
*
|
|
33
37
|
* @returns {Array|Object} Flattened result
|
|
34
38
|
*
|
|
39
|
+
* @throws {TypeError} When two entries flatten to the same key, eg. the key
|
|
40
|
+
* `"user.role"` next to `{ user: { role } }`
|
|
41
|
+
*
|
|
35
42
|
* @example
|
|
36
43
|
* flatten([1, [2], [3, [4]]])
|
|
37
44
|
* // => [1, 2, 3, 4]
|
|
@@ -15,7 +15,7 @@ const _flattenArray = (input, level, result = [])=>{
|
|
|
15
15
|
return result;
|
|
16
16
|
};
|
|
17
17
|
// `ancestors` holds the objects above `input`: an object that contains itself
|
|
18
|
-
// is kept as a leaf
|
|
18
|
+
// is kept as a leaf
|
|
19
19
|
const _flattenObject = (input, separator, prefix, result, ancestors)=>{
|
|
20
20
|
ancestors.add(input);
|
|
21
21
|
const keys = Object.keys(input);
|
|
@@ -27,6 +27,12 @@ const _flattenObject = (input, separator, prefix, result, ancestors)=>{
|
|
|
27
27
|
if (isPlainObject(value) && Object.keys(value).length !== 0 && !ancestors.has(value)) {
|
|
28
28
|
_flattenObject(value, separator, fullKey, result, ancestors);
|
|
29
29
|
} else {
|
|
30
|
+
// A key that contains the separator lands on the key of a nested path,
|
|
31
|
+
// eg. "user.role" and { user: { role } }. Throw, as unflatten does,
|
|
32
|
+
// rather than let the last one win
|
|
33
|
+
if (Object.hasOwn(result, fullKey)) {
|
|
34
|
+
throw new TypeError(`@asd14/m/flatten: expected '${fullKey}' to be 'Unique', got 'Duplicate'`);
|
|
35
|
+
}
|
|
30
36
|
_setOwn(result, fullKey, value);
|
|
31
37
|
}
|
|
32
38
|
}
|
|
@@ -44,6 +50,10 @@ const _flatten = (input, level, separator)=>{
|
|
|
44
50
|
* For arrays, concatenates all nested arrays into a single flat array.
|
|
45
51
|
* For objects, joins nested keys with a separator into a flat structure.
|
|
46
52
|
*
|
|
53
|
+
* It recurses, so the stack limits the depth: an object nested a few thousand
|
|
54
|
+
* levels deep throws a `RangeError`. `JSON.parse` accepts any depth, so check
|
|
55
|
+
* the depth of untrusted input first, if it can be that deep.
|
|
56
|
+
*
|
|
47
57
|
* Input is never mutated - always returns a new array or object.
|
|
48
58
|
*
|
|
49
59
|
* Only a plain object is flattened. An empty object, a `Date`, a `Map` and a
|
|
@@ -58,6 +68,9 @@ const _flatten = (input, level, separator)=>{
|
|
|
58
68
|
*
|
|
59
69
|
* @returns {Array|Object} Flattened result
|
|
60
70
|
*
|
|
71
|
+
* @throws {TypeError} When two entries flatten to the same key, eg. the key
|
|
72
|
+
* `"user.role"` next to `{ user: { role } }`
|
|
73
|
+
*
|
|
61
74
|
* @example
|
|
62
75
|
* flatten([1, [2], [3, [4]]])
|
|
63
76
|
* // => [1, 2, 3, 4]
|
|
@@ -18,6 +18,9 @@ type FuzzyMatchFn = {
|
|
|
18
18
|
* word start or at a camelCase hump, and a shorter text. Scores lower: each
|
|
19
19
|
* gap between two letters.
|
|
20
20
|
*
|
|
21
|
+
* The time grows with the query length times the text length: cap a query
|
|
22
|
+
* from untrusted input, eg. at 100 letters.
|
|
23
|
+
*
|
|
21
24
|
* Input is never mutated.
|
|
22
25
|
*
|
|
23
26
|
* @param {string} query - Letters to find, in order
|
|
@@ -36,14 +36,77 @@ const scoreBonus = (text, index)=>{
|
|
|
36
36
|
}
|
|
37
37
|
return isLowerCase(previous) && isUpperCase(text.charAt(index)) ? BONUS_CAMEL_HUMP : 0;
|
|
38
38
|
};
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
|
|
39
|
+
const widenGap = (gap, opening)=>{
|
|
40
|
+
// Each index the gap already spans costs a little more
|
|
41
|
+
if (gap.cell) {
|
|
42
|
+
gap.score -= PENALTY_GAP_EXTENSION;
|
|
42
43
|
}
|
|
43
|
-
|
|
44
|
-
|
|
44
|
+
// A cell two indexes back can start a new gap. On a tie, the open gap stays
|
|
45
|
+
if (opening && (!gap.cell || opening.score - PENALTY_GAP_START > gap.score)) {
|
|
46
|
+
gap.cell = opening;
|
|
47
|
+
gap.score = opening.score - PENALTY_GAP_START;
|
|
45
48
|
}
|
|
46
|
-
|
|
49
|
+
};
|
|
50
|
+
// The first query letter: no letter before it to link to
|
|
51
|
+
const startCell = (text, index)=>({
|
|
52
|
+
score: SCORE_MATCH + scoreBonus(text, index) * FIRST_LETTER_MULTIPLIER,
|
|
53
|
+
index,
|
|
54
|
+
previous: undefined
|
|
55
|
+
});
|
|
56
|
+
// A later query letter links to the letter before it: right before this
|
|
57
|
+
// index, or across the gap. On a tie, the consecutive letter wins
|
|
58
|
+
const extendCell = (text, index, consecutive, gap)=>{
|
|
59
|
+
if (!consecutive && !gap.cell) {
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
const bonus = scoreBonus(text, index);
|
|
63
|
+
const consecutiveScore = consecutive ? consecutive.score + Math.max(bonus, BONUS_CONSECUTIVE) : Number.NEGATIVE_INFINITY;
|
|
64
|
+
const gapScore = gap.cell ? gap.score + bonus : Number.NEGATIVE_INFINITY;
|
|
65
|
+
const isGapBetter = gapScore > consecutiveScore;
|
|
66
|
+
return {
|
|
67
|
+
score: (isGapBetter ? gapScore : consecutiveScore) + SCORE_MATCH,
|
|
68
|
+
index,
|
|
69
|
+
previous: isGapBetter ? gap.cell : consecutive
|
|
70
|
+
};
|
|
71
|
+
};
|
|
72
|
+
// The row of one query letter, from the row of the letter before it. Returns
|
|
73
|
+
// undefined when the letter matches nowhere. `lowerText` is the text in lower
|
|
74
|
+
// case, when lowering kept its length
|
|
75
|
+
const matchLetter = (letter, text, lowerText, previousRow, isFirstLetter)=>{
|
|
76
|
+
const row = [];
|
|
77
|
+
const gap = {
|
|
78
|
+
cell: undefined,
|
|
79
|
+
score: 0
|
|
80
|
+
};
|
|
81
|
+
// A letter whose lower case is 2 code units, eg. "İ", cannot equal one
|
|
82
|
+
// character of a text that kept its length in lower case
|
|
83
|
+
const letterCode = letter.length === 1 ? letter.charCodeAt(0) : -1;
|
|
84
|
+
let hasCell = false;
|
|
85
|
+
for(let index = 0, length = text.length; index < length; index++){
|
|
86
|
+
widenGap(gap, previousRow[index - 2]);
|
|
87
|
+
const isMatch = lowerText ? lowerText.charCodeAt(index) === letterCode : text.charAt(index).toLowerCase() === letter;
|
|
88
|
+
if (!isMatch) {
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
const cell = isFirstLetter ? startCell(text, index) : extendCell(text, index, previousRow[index - 1], gap);
|
|
92
|
+
if (cell) {
|
|
93
|
+
row[index] = cell;
|
|
94
|
+
hasCell = true;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return hasCell ? row : undefined;
|
|
98
|
+
};
|
|
99
|
+
// On a tie, keeps `a`: the placement found first
|
|
100
|
+
const pickBest = (a, b)=>!a || b && b.score > a.score ? b : a;
|
|
101
|
+
// The text index of each letter, following the links back from `cell`
|
|
102
|
+
const toIndexes = (cell)=>{
|
|
103
|
+
const indexes = [];
|
|
104
|
+
let current = cell;
|
|
105
|
+
while(current){
|
|
106
|
+
indexes.push(current.index);
|
|
107
|
+
current = current.previous;
|
|
108
|
+
}
|
|
109
|
+
return indexes.reverse();
|
|
47
110
|
};
|
|
48
111
|
const _fuzzyMatch = (query, text)=>{
|
|
49
112
|
if (typeof text !== "string") {
|
|
@@ -55,63 +118,33 @@ const _fuzzyMatch = (query, text)=>{
|
|
|
55
118
|
indexes: []
|
|
56
119
|
};
|
|
57
120
|
}
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
121
|
+
// Each query letter needs its own index in the text
|
|
122
|
+
if (query.length > text.length) {
|
|
123
|
+
return undefined;
|
|
124
|
+
}
|
|
125
|
+
// Lower the text once and compare character codes: about a quarter faster
|
|
126
|
+
// for a short query over many texts. A text whose lower case has another
|
|
127
|
+
// length, eg. one with "İ", compares letter by letter, so each index still
|
|
128
|
+
// points into the text
|
|
129
|
+
const lowered = text.toLowerCase();
|
|
130
|
+
const lowerText = lowered.length === text.length ? lowered : undefined;
|
|
131
|
+
let row = [];
|
|
62
132
|
for(let queryIndex = 0; queryIndex < query.length; queryIndex++){
|
|
63
133
|
const letter = query.charAt(queryIndex).toLowerCase();
|
|
64
|
-
const
|
|
65
|
-
//
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
row = [];
|
|
69
|
-
for(let textIndex = 0; textIndex < text.length; textIndex++){
|
|
70
|
-
const opening = previousRow[textIndex - 2];
|
|
71
|
-
gap = pickBest(gap && {
|
|
72
|
-
score: gap.score - PENALTY_GAP_EXTENSION,
|
|
73
|
-
indexes: gap.indexes
|
|
74
|
-
}, opening && {
|
|
75
|
-
score: opening.score - PENALTY_GAP_START,
|
|
76
|
-
indexes: opening.indexes
|
|
77
|
-
});
|
|
78
|
-
if (text.charAt(textIndex).toLowerCase() !== letter) {
|
|
79
|
-
continue;
|
|
80
|
-
}
|
|
81
|
-
const bonus = scoreBonus(text, textIndex);
|
|
82
|
-
if (queryIndex === 0) {
|
|
83
|
-
row[textIndex] = {
|
|
84
|
-
score: SCORE_MATCH + bonus * FIRST_LETTER_MULTIPLIER,
|
|
85
|
-
indexes: [
|
|
86
|
-
textIndex
|
|
87
|
-
]
|
|
88
|
-
};
|
|
89
|
-
continue;
|
|
90
|
-
}
|
|
91
|
-
const consecutive = previousRow[textIndex - 1];
|
|
92
|
-
const best = pickBest(consecutive && {
|
|
93
|
-
score: consecutive.score + Math.max(bonus, BONUS_CONSECUTIVE),
|
|
94
|
-
indexes: consecutive.indexes
|
|
95
|
-
}, gap && {
|
|
96
|
-
score: gap.score + bonus,
|
|
97
|
-
indexes: gap.indexes
|
|
98
|
-
});
|
|
99
|
-
row[textIndex] = best && {
|
|
100
|
-
score: best.score + SCORE_MATCH,
|
|
101
|
-
indexes: [
|
|
102
|
-
...best.indexes,
|
|
103
|
-
textIndex
|
|
104
|
-
]
|
|
105
|
-
};
|
|
134
|
+
const nextRow = matchLetter(letter, text, lowerText, row, queryIndex === 0);
|
|
135
|
+
// This letter matched nowhere, so the rest of the query cannot match
|
|
136
|
+
if (!nextRow) {
|
|
137
|
+
return undefined;
|
|
106
138
|
}
|
|
139
|
+
row = nextRow;
|
|
107
140
|
}
|
|
108
141
|
let best;
|
|
109
|
-
for(
|
|
110
|
-
best = pickBest(best,
|
|
142
|
+
for (const cell of row){
|
|
143
|
+
best = pickBest(best, cell);
|
|
111
144
|
}
|
|
112
145
|
return best && {
|
|
113
146
|
score: best.score - text.length * PENALTY_TEXT_LENGTH,
|
|
114
|
-
indexes: best
|
|
147
|
+
indexes: toIndexes(best)
|
|
115
148
|
};
|
|
116
149
|
};
|
|
117
150
|
/**
|
|
@@ -124,6 +157,9 @@ const _fuzzyMatch = (query, text)=>{
|
|
|
124
157
|
* word start or at a camelCase hump, and a shorter text. Scores lower: each
|
|
125
158
|
* gap between two letters.
|
|
126
159
|
*
|
|
160
|
+
* The time grows with the query length times the text length: cap a query
|
|
161
|
+
* from untrusted input, eg. at 100 letters.
|
|
162
|
+
*
|
|
127
163
|
* Input is never mutated.
|
|
128
164
|
*
|
|
129
165
|
* @param {string} query - Letters to find, in order
|
|
@@ -3,22 +3,22 @@ type GroupByFn = {
|
|
|
3
3
|
<T1, T2, T3>(fns: [
|
|
4
4
|
UnaryMorphism<T1, T2>,
|
|
5
5
|
UnaryMorphism<T2, T3>,
|
|
6
|
-
UnaryMorphism<T3, string>
|
|
6
|
+
UnaryMorphism<T3, string | number>
|
|
7
7
|
], input: readonly T1[]): Record<string, T1[]>;
|
|
8
8
|
<T1, T2, T3>(fns: [
|
|
9
9
|
UnaryMorphism<T1, T2>,
|
|
10
10
|
UnaryMorphism<T2, T3>,
|
|
11
|
-
UnaryMorphism<T3, string>
|
|
11
|
+
UnaryMorphism<T3, string | number>
|
|
12
12
|
]): (input: readonly T1[]) => Record<string, T1[]>;
|
|
13
|
-
<T1, T2>(fns: [UnaryMorphism<T1, T2>, UnaryMorphism<T2, string>], input: readonly T1[]): Record<string, T1[]>;
|
|
14
|
-
<T1, T2>(fns: [UnaryMorphism<T1, T2>, UnaryMorphism<T2, string>]): (input: readonly T1[]) => Record<string, T1[]>;
|
|
15
|
-
<T>(fn: (item: T) => string, input: readonly T[]): Record<string, T[]>;
|
|
16
|
-
<T>(fn: (item: T) => string): (input: readonly T[]) => Record<string, T[]>;
|
|
13
|
+
<T1, T2>(fns: [UnaryMorphism<T1, T2>, UnaryMorphism<T2, string | number>], input: readonly T1[]): Record<string, T1[]>;
|
|
14
|
+
<T1, T2>(fns: [UnaryMorphism<T1, T2>, UnaryMorphism<T2, string | number>]): (input: readonly T1[]) => Record<string, T1[]>;
|
|
15
|
+
<T>(fn: (item: T) => string | number, input: readonly T[]): Record<string, T[]>;
|
|
16
|
+
<T>(fn: (item: T) => string | number): (input: readonly T[]) => Record<string, T[]>;
|
|
17
17
|
};
|
|
18
18
|
/**
|
|
19
19
|
* Group the items of an array by the key a function returns for each. Returns
|
|
20
20
|
* an object where each key holds the array of its items, in input order. The
|
|
21
|
-
*
|
|
21
|
+
* function returns a string or a number, and the key is its string form.
|
|
22
22
|
*
|
|
23
23
|
* Only own keys count, so `"constructor"`, `"toString"` and `"__proto__"` work
|
|
24
24
|
* as group keys.
|
|
@@ -30,6 +30,9 @@ type GroupByFn = {
|
|
|
30
30
|
*
|
|
31
31
|
* @returns {Object} Object of arrays, one for each key
|
|
32
32
|
*
|
|
33
|
+
* @throws {TypeError} When `fn` returns neither a string nor a number, eg.
|
|
34
|
+
* `expected 'fn(input[1])' to be 'String' or 'Number', got 'Undefined'`
|
|
35
|
+
*
|
|
33
36
|
* @example
|
|
34
37
|
* groupBy(user => user.role, [
|
|
35
38
|
* { name: "alice", role: "admin" },
|
|
@@ -44,6 +47,15 @@ type GroupByFn = {
|
|
|
44
47
|
* groupBy(n => n % 2 === 0 ? "even" : "odd")([1, 2, 3, 4, 5])
|
|
45
48
|
* // => { odd: [1, 3, 5], even: [2, 4] }
|
|
46
49
|
*
|
|
50
|
+
* groupBy(read("level"), [{ level: 1 }, { level: 2 }, { level: 1 }])
|
|
51
|
+
* // => { "1": [{ level: 1 }, { level: 1 }], "2": [{ level: 2 }] }
|
|
52
|
+
*
|
|
53
|
+
* // A String step turns any key into a string. To split by a boolean,
|
|
54
|
+
* // `partition(read("active"))` is the intended tool: it returns both
|
|
55
|
+
* // groups as a pair
|
|
56
|
+
* groupBy([read("active"), String], [{ active: true }, { active: false }])
|
|
57
|
+
* // => { true: [{ active: true }], false: [{ active: false }] }
|
|
58
|
+
*
|
|
47
59
|
* // A pipe array builds the key in steps
|
|
48
60
|
* groupBy([read("role"), role => role.toUpperCase()], users)
|
|
49
61
|
* // => { ADMIN: [...], USER: [...] }
|
|
@@ -8,7 +8,13 @@ const _groupBy = (fn, input)=>{
|
|
|
8
8
|
const result = {};
|
|
9
9
|
for(let i = 0, length = input.length; i < length; i++){
|
|
10
10
|
const item = input[i];
|
|
11
|
-
const
|
|
11
|
+
const rawKey = fn(item);
|
|
12
|
+
// The types allow a string or a number. Anything else would turn into a
|
|
13
|
+
// string that can match another item's key, eg. ["admin"] into "admin"
|
|
14
|
+
if (typeof rawKey !== "string" && typeof rawKey !== "number") {
|
|
15
|
+
throw new TypeError(`@asd14/m/groupBy: expected 'fn(input[${i}])' to be 'String' or 'Number', got '${type(rawKey)}'`);
|
|
16
|
+
}
|
|
17
|
+
const key = String(rawKey);
|
|
12
18
|
if (Object.hasOwn(result, key)) {
|
|
13
19
|
result[key].push(item);
|
|
14
20
|
} else {
|
|
@@ -22,7 +28,7 @@ const _groupBy = (fn, input)=>{
|
|
|
22
28
|
/**
|
|
23
29
|
* Group the items of an array by the key a function returns for each. Returns
|
|
24
30
|
* an object where each key holds the array of its items, in input order. The
|
|
25
|
-
*
|
|
31
|
+
* function returns a string or a number, and the key is its string form.
|
|
26
32
|
*
|
|
27
33
|
* Only own keys count, so `"constructor"`, `"toString"` and `"__proto__"` work
|
|
28
34
|
* as group keys.
|
|
@@ -34,6 +40,9 @@ const _groupBy = (fn, input)=>{
|
|
|
34
40
|
*
|
|
35
41
|
* @returns {Object} Object of arrays, one for each key
|
|
36
42
|
*
|
|
43
|
+
* @throws {TypeError} When `fn` returns neither a string nor a number, eg.
|
|
44
|
+
* `expected 'fn(input[1])' to be 'String' or 'Number', got 'Undefined'`
|
|
45
|
+
*
|
|
37
46
|
* @example
|
|
38
47
|
* groupBy(user => user.role, [
|
|
39
48
|
* { name: "alice", role: "admin" },
|
|
@@ -48,6 +57,15 @@ const _groupBy = (fn, input)=>{
|
|
|
48
57
|
* groupBy(n => n % 2 === 0 ? "even" : "odd")([1, 2, 3, 4, 5])
|
|
49
58
|
* // => { odd: [1, 3, 5], even: [2, 4] }
|
|
50
59
|
*
|
|
60
|
+
* groupBy(read("level"), [{ level: 1 }, { level: 2 }, { level: 1 }])
|
|
61
|
+
* // => { "1": [{ level: 1 }, { level: 1 }], "2": [{ level: 2 }] }
|
|
62
|
+
*
|
|
63
|
+
* // A String step turns any key into a string. To split by a boolean,
|
|
64
|
+
* // `partition(read("active"))` is the intended tool: it returns both
|
|
65
|
+
* // groups as a pair
|
|
66
|
+
* groupBy([read("active"), String], [{ active: true }, { active: false }])
|
|
67
|
+
* // => { true: [{ active: true }], false: [{ active: false }] }
|
|
68
|
+
*
|
|
51
69
|
* // A pipe array builds the key in steps
|
|
52
70
|
* groupBy([read("role"), role => role.toUpperCase()], users)
|
|
53
71
|
* // => { ADMIN: [...], USER: [...] }
|