@asd14/m 9.1.0 → 11.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.
Files changed (54) hide show
  1. package/dist/src/debounce/debounce.d.ts +13 -1
  2. package/dist/src/debounce/debounce.js +27 -20
  3. package/dist/src/distinct/by/distinct-by.d.ts +3 -0
  4. package/dist/src/distinct/by/distinct-by.js +3 -0
  5. package/dist/src/distinct/distinct.js +12 -3
  6. package/dist/src/escape/escape.js +6 -1
  7. package/dist/src/escape/html/escape-html.d.ts +17 -2
  8. package/dist/src/escape/html/escape-html.js +17 -2
  9. package/dist/src/escape/reg-exp/escape-reg-exp.d.ts +3 -2
  10. package/dist/src/escape/reg-exp/escape-reg-exp.js +11 -4
  11. package/dist/src/flatten/flatten.d.ts +38 -26
  12. package/dist/src/flatten/flatten.js +94 -36
  13. package/dist/src/fuzzy-match/fuzzy-match.d.ts +3 -0
  14. package/dist/src/fuzzy-match/fuzzy-match.js +91 -55
  15. package/dist/src/group/group-by.d.ts +3 -0
  16. package/dist/src/group/group-by.js +10 -1
  17. package/dist/src/index-by/index-by.d.ts +3 -0
  18. package/dist/src/index-by/index-by.js +10 -1
  19. package/dist/src/index.d.ts +0 -1
  20. package/dist/src/index.js +0 -1
  21. package/dist/src/intersect/by/intersect-by.d.ts +3 -0
  22. package/dist/src/intersect/by/intersect-by.js +3 -0
  23. package/dist/src/is-deep-equal/is-deep-equal.d.ts +20 -5
  24. package/dist/src/is-deep-equal/is-deep-equal.js +44 -7
  25. package/dist/src/is-match/is-match.d.ts +4 -0
  26. package/dist/src/is-match/is-match.js +4 -0
  27. package/dist/src/is-uri/is-uri.js +12 -9
  28. package/dist/src/merge/merge.d.ts +5 -1
  29. package/dist/src/merge/merge.js +12 -6
  30. package/dist/src/pick/pick.js +7 -0
  31. package/dist/src/throttle/throttle.d.ts +11 -1
  32. package/dist/src/throttle/throttle.js +49 -43
  33. package/dist/src/unite/by/unite-by.d.ts +3 -0
  34. package/dist/src/unite/by/unite-by.js +3 -0
  35. package/dist/src/update/update.d.ts +2 -2
  36. package/dist/src/utils/build-patch.js +3 -1
  37. package/dist/src/utils/parse-timer-options.d.ts +22 -0
  38. package/dist/src/utils/parse-timer-options.js +44 -0
  39. package/dist/src/utils/set-own.d.ts +5 -4
  40. package/dist/src/utils/set-own.js +6 -5
  41. package/dist/src/write/write.d.ts +3 -4
  42. package/dist/src/zip-to-object/zip-to-object.js +7 -0
  43. package/dist/types/array.d.ts +12 -0
  44. package/dist/types/object.d.ts +8 -4
  45. package/dist/types/object.matcher.d.ts +4 -2
  46. package/docs/SPEC.md +11 -11
  47. package/docs/how-to/jsdoc.md +33 -14
  48. package/docs/how-to/prototype-pollution-tests.md +156 -0
  49. package/docs/how-to/tape-runtime-tests.md +49 -23
  50. package/docs/how-to/tstyche-type-tests.md +49 -14
  51. package/docs/how-to/writing-functions.md +26 -0
  52. package/package.json +10 -7
  53. package/dist/src/evolve/deep-by/evolve-deep-by.d.ts +0 -65
  54. 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
- const _debounce = (fn, wait)=>{
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
- let wait = 50;
42
- if (params.length > 1) {
43
- const options = params[0];
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
- return distinctBy(isEqual, input);
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 };
@@ -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
- return input.replace(match, "\\$&");
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,7 +1,20 @@
1
1
  type EscapeHTMLFn = (input: string) => string;
2
2
  /**
3
- * Escape HTML special characters in a string so it can be safely embedded
4
- * in an HTML document without being interpreted as markup.
3
+ * Escape the HTML special characters of a string, `"&'/<>`, so it can be
4
+ * embedded as text: in element content, eg. `<p>…</p>`.
5
+ *
6
+ * It is not safe anywhere else:
7
+ *
8
+ * - an unquoted attribute value: a space starts a new attribute, eg.
9
+ * `<input value=${escapeHTML("x onfocus=alert(1)")}>`
10
+ * - an event handler, eg. `onclick`: its value is code, so the text runs,
11
+ * eg. `alert(1)`. The browser also decodes `&#39;` back to `'` first
12
+ * - a URL attribute, eg. `href` or `src`: `javascript:alert(1)` comes back
13
+ * unchanged. Allow only some schemes, eg. `https:`, and encode a part of
14
+ * the URL with `encodeURIComponent`
15
+ * - the content of `<script>` or `<style>`: they decode no entities, so the
16
+ * text runs as code. Use `JSON.stringify` for a value in a script, and
17
+ * `CSS.escape` for a CSS value
5
18
  *
6
19
  * Input is never mutated - always returns a new string.
7
20
  *
@@ -10,6 +23,8 @@ type EscapeHTMLFn = (input: string) => string;
10
23
  * @returns {string} String with HTML special characters escaped
11
24
  *
12
25
  * @example
26
+ * `<p>${escapeHTML(bio)}</p>`
27
+ *
13
28
  * escapeHTML("<b>bold</b>")
14
29
  * // => "&lt;b&gt;bold&lt;&#47;b&gt;"
15
30
  *
@@ -9,8 +9,21 @@ const CHAR_MAP = {
9
9
  };
10
10
  const HTML_SPECIAL = /["&'/<>]/g;
11
11
  /**
12
- * Escape HTML special characters in a string so it can be safely embedded
13
- * in an HTML document without being interpreted as markup.
12
+ * Escape the HTML special characters of a string, `"&'/<>`, so it can be
13
+ * embedded as text: in element content, eg. `<p>…</p>`.
14
+ *
15
+ * It is not safe anywhere else:
16
+ *
17
+ * - an unquoted attribute value: a space starts a new attribute, eg.
18
+ * `<input value=${escapeHTML("x onfocus=alert(1)")}>`
19
+ * - an event handler, eg. `onclick`: its value is code, so the text runs,
20
+ * eg. `alert(1)`. The browser also decodes `&#39;` back to `'` first
21
+ * - a URL attribute, eg. `href` or `src`: `javascript:alert(1)` comes back
22
+ * unchanged. Allow only some schemes, eg. `https:`, and encode a part of
23
+ * the URL with `encodeURIComponent`
24
+ * - the content of `<script>` or `<style>`: they decode no entities, so the
25
+ * text runs as code. Use `JSON.stringify` for a value in a script, and
26
+ * `CSS.escape` for a CSS value
14
27
  *
15
28
  * Input is never mutated - always returns a new string.
16
29
  *
@@ -19,6 +32,8 @@ const HTML_SPECIAL = /["&'/<>]/g;
19
32
  * @returns {string} String with HTML special characters escaped
20
33
  *
21
34
  * @example
35
+ * `<p>${escapeHTML(bio)}</p>`
36
+ *
22
37
  * escapeHTML("<b>bold</b>")
23
38
  * // => "&lt;b&gt;bold&lt;&#47;b&gt;"
24
39
  *
@@ -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, also in a character class
5
- * and with the `u` flag.
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 = /[$()*+\-.?[\\\]^{|}]/g;
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, also in a character class
6
- * and with the `u` flag.
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 };
@@ -1,37 +1,46 @@
1
1
  import type { PlainObject } from "../../types/object.js";
2
2
  type DeepFlatten<T> = T extends readonly (infer U)[] ? DeepFlatten<U> : T;
3
3
  type FlattenLevel<T, Level extends number, Depth extends unknown[] = []> = number extends Level ? unknown : T extends readonly (infer U)[] ? Depth["length"] extends Level ? T : FlattenLevel<U, Level, [...Depth, unknown]> : T;
4
- type FlattenObjectOptions = {
5
- separator: string;
6
- };
4
+ type FlattenInputFor<LevelOrSeparator> = LevelOrSeparator extends number ? readonly unknown[] : LevelOrSeparator extends string ? PlainObject : never;
5
+ type FlattenOne<First> = First extends number ? <T>(input: readonly T[]) => FlattenLevel<T, First>[] : First extends string ? (input: PlainObject) => PlainObject : First extends readonly (infer T)[] ? DeepFlatten<T>[] : First extends PlainObject ? PlainObject : never;
7
6
  type FlattenFn = {
8
- <T, const Level extends number>(options: {
9
- level: Level;
10
- }, input: readonly T[]): FlattenLevel<T, Level>[];
11
- (options: FlattenObjectOptions, input: PlainObject): PlainObject;
12
- <T>(input: readonly T[]): DeepFlatten<T>[];
13
- (input: PlainObject): PlainObject;
7
+ <First extends number | string | readonly unknown[] | PlainObject>(levelSeparatorOrInput: First): FlattenOne<First>;
8
+ <LevelOrSeparator extends number | string, I extends FlattenInputFor<LevelOrSeparator>>(levelOrSeparator: LevelOrSeparator, input: I): LevelOrSeparator extends number ? I extends readonly (infer T)[] ? FlattenLevel<T, LevelOrSeparator>[] : never : LevelOrSeparator extends string ? PlainObject : never;
14
9
  };
15
10
  /**
16
- * Recursively flatten nested arrays or objects.
11
+ * Flatten nested arrays or objects.
17
12
  *
18
- * For arrays, concatenates all nested arrays into a single flat array.
13
+ * For arrays, concatenates nested arrays into a single flat array, down to
14
+ * `level` levels.
19
15
  * For objects, joins nested keys with a separator into a flat structure.
20
16
  *
17
+ * It recurses, so the stack limits the depth: an array or an object nested a
18
+ * few thousand levels deep throws a `RangeError`. `JSON.parse` accepts any
19
+ * depth, so check the depth of untrusted input first, if it can be that deep.
20
+ *
21
21
  * Input is never mutated - always returns a new array or object.
22
22
  *
23
23
  * Only a plain object is flattened. An empty object, a `Date`, a `Map` and a
24
- * class instance stay as values, and so does an object that contains itself.
25
- * `level` counts the array levels to flatten, `Infinity` by default.
24
+ * class instance stay as values. An array or an object that contains itself
25
+ * stays as a value too.
26
26
  *
27
- * Options go only in the two-argument form. With one argument, `flatten`
28
- * flattens it, even an object with a `level` or `separator` key.
27
+ * A number before an array is the level, the number of array levels to
28
+ * flatten, `Infinity` by default. For all levels, call `flatten(input)`:
29
+ * `Infinity` is a `number` to TypeScript, so `flatten(Infinity, input)` returns
30
+ * `unknown[]`. A string before an object is the separator, `"."` by default.
31
+ * With either alone, `flatten` returns a pipe step. One object alone is the
32
+ * input, even with a `level` or `separator` key.
29
33
  *
30
- * @param {Object} [options] - { level: number } for arrays, { separator: string } for objects
34
+ * @param {number|string} [levelOrSeparator] - The level for an array, or the separator for an object
31
35
  * @param {Array|Object} input - Array or object to flatten
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
+ * `@asd14/m/flatten: expected 'user.role' to be 'Unique', got 'Duplicate'`
42
+ * @throws {RangeError} When the input is nested deeper than the stack allows
43
+ *
35
44
  * @example
36
45
  * flatten([1, [2], [3, [4]]])
37
46
  * // => [1, 2, 3, 4]
@@ -39,26 +48,29 @@ type FlattenFn = {
39
48
  * flatten({ a: { b: 1, c: { d: 2 } } })
40
49
  * // => { "a.b": 1, "a.c.d": 2 }
41
50
  *
42
- * flatten({ level: 1 }, [1, [2, [3]]])
51
+ * flatten(1, [1, [2, [3]]])
43
52
  * // => [1, 2, [3]]
44
53
  *
45
- * flatten({ separator: "__" }, { a: { b: 1 } })
54
+ * flatten("__", { a: { b: 1 } })
46
55
  * // => { a__b: 1 }
47
56
  *
57
+ * pipe(read("tags"), flatten(1))({
58
+ * tags: [[1], [2, [3]]]
59
+ * })
60
+ * // => [1, 2, [3]]
61
+ *
62
+ * pipe(read("meta"), flatten("/"))({
63
+ * meta: { a: { b: 1 } }
64
+ * })
65
+ * // => { "a/b": 1 }
66
+ *
48
67
  * flatten({ a: {}, b: { c: new Date(0) } })
49
68
  * // => { a: {}, "b.c": new Date(0) }
50
69
  *
51
- * pipe(
52
- * map(read("tags")),
53
- * flatten,
54
- * distinct
55
- * )([{ tags: ["a"] }, { tags: ["a", "b"] }])
56
- * // => ["a", "b"]
57
- *
58
70
  * @name flatten
59
71
  * @tag Array
60
72
  *
61
- * @see {@link unflatten}
73
+ * @see {@link unflatten} to rebuild the nested object from the flat keys
62
74
  */
63
75
  declare const flatten: FlattenFn;
64
76
  export { flatten };
@@ -2,20 +2,23 @@ import { isPlainObject } from "../is/is.js";
2
2
  import { type } from "../type/type.js";
3
3
  import { _setOwn } from "../utils/set-own.js";
4
4
  // Pushes into `result`: a spread of a large child array into `push` would
5
- // overflow the call stack
6
- const _flattenArray = (input, level, result = [])=>{
5
+ // overflow the call stack. `ancestors` holds the arrays above `input`: an
6
+ // array that contains itself is kept as an item, as in `_flattenObject`
7
+ const _flattenArray = (input, level, result = [], ancestors = new WeakSet())=>{
8
+ ancestors.add(input);
7
9
  for(let i = 0, length = input.length; i < length; i++){
8
10
  const item = input[i];
9
- if (level > 0 && Array.isArray(item)) {
10
- _flattenArray(item, level - 1, result);
11
+ if (level > 0 && Array.isArray(item) && !ancestors.has(item)) {
12
+ _flattenArray(item, level - 1, result, ancestors);
11
13
  } else {
12
14
  result.push(item);
13
15
  }
14
16
  }
17
+ ancestors.delete(input);
15
18
  return result;
16
19
  };
17
20
  // `ancestors` holds the objects above `input`: an object that contains itself
18
- // is kept as a leaf, as in `evolveDeepBy`
21
+ // is kept as a leaf
19
22
  const _flattenObject = (input, separator, prefix, result, ancestors)=>{
20
23
  ancestors.add(input);
21
24
  const keys = Object.keys(input);
@@ -27,6 +30,12 @@ const _flattenObject = (input, separator, prefix, result, ancestors)=>{
27
30
  if (isPlainObject(value) && Object.keys(value).length !== 0 && !ancestors.has(value)) {
28
31
  _flattenObject(value, separator, fullKey, result, ancestors);
29
32
  } else {
33
+ // A key that contains the separator lands on the key of a nested path,
34
+ // eg. "user.role" and { user: { role } }. Throw, as unflatten does,
35
+ // rather than let the last one win
36
+ if (Object.hasOwn(result, fullKey)) {
37
+ throw new TypeError(`@asd14/m/flatten: expected '${fullKey}' to be 'Unique', got 'Duplicate'`);
38
+ }
30
39
  _setOwn(result, fullKey, value);
31
40
  }
32
41
  }
@@ -34,30 +43,62 @@ const _flattenObject = (input, separator, prefix, result, ancestors)=>{
34
43
  return result;
35
44
  };
36
45
  const _flatten = (input, level, separator)=>{
37
- if (Array.isArray(input)) return _flattenArray(input, level);
38
- if (isPlainObject(input)) return _flattenObject(input, separator, undefined, {}, new WeakSet());
46
+ if (Array.isArray(input)) {
47
+ return _flattenArray(input, level);
48
+ }
49
+ if (isPlainObject(input)) {
50
+ return _flattenObject(input, separator, undefined, {}, new WeakSet());
51
+ }
39
52
  throw new TypeError(`@asd14/m/flatten: expected 'input' to be 'Array' or 'Object', got '${type(input)}'`);
40
53
  };
54
+ // Flatten `level` levels of an array
55
+ const _flattenLevels = (level, input)=>{
56
+ if (!Array.isArray(input)) {
57
+ throw new TypeError(`@asd14/m/flatten: expected 'input' to be 'Array', got '${type(input)}'`);
58
+ }
59
+ return _flattenArray(input, level);
60
+ };
61
+ // Flatten the keys of an object, joined with `separator`
62
+ const _flattenKeys = (separator, input)=>{
63
+ if (!isPlainObject(input)) {
64
+ throw new TypeError(`@asd14/m/flatten: expected 'input' to be 'Object', got '${type(input)}'`);
65
+ }
66
+ return _flattenObject(input, separator, undefined, {}, new WeakSet());
67
+ };
41
68
  /**
42
- * Recursively flatten nested arrays or objects.
69
+ * Flatten nested arrays or objects.
43
70
  *
44
- * For arrays, concatenates all nested arrays into a single flat array.
71
+ * For arrays, concatenates nested arrays into a single flat array, down to
72
+ * `level` levels.
45
73
  * For objects, joins nested keys with a separator into a flat structure.
46
74
  *
75
+ * It recurses, so the stack limits the depth: an array or an object nested a
76
+ * few thousand levels deep throws a `RangeError`. `JSON.parse` accepts any
77
+ * depth, so check the depth of untrusted input first, if it can be that deep.
78
+ *
47
79
  * Input is never mutated - always returns a new array or object.
48
80
  *
49
81
  * Only a plain object is flattened. An empty object, a `Date`, a `Map` and a
50
- * class instance stay as values, and so does an object that contains itself.
51
- * `level` counts the array levels to flatten, `Infinity` by default.
82
+ * class instance stay as values. An array or an object that contains itself
83
+ * stays as a value too.
52
84
  *
53
- * Options go only in the two-argument form. With one argument, `flatten`
54
- * flattens it, even an object with a `level` or `separator` key.
85
+ * A number before an array is the level, the number of array levels to
86
+ * flatten, `Infinity` by default. For all levels, call `flatten(input)`:
87
+ * `Infinity` is a `number` to TypeScript, so `flatten(Infinity, input)` returns
88
+ * `unknown[]`. A string before an object is the separator, `"."` by default.
89
+ * With either alone, `flatten` returns a pipe step. One object alone is the
90
+ * input, even with a `level` or `separator` key.
55
91
  *
56
- * @param {Object} [options] - { level: number } for arrays, { separator: string } for objects
92
+ * @param {number|string} [levelOrSeparator] - The level for an array, or the separator for an object
57
93
  * @param {Array|Object} input - Array or object to flatten
58
94
  *
59
95
  * @returns {Array|Object} Flattened result
60
96
  *
97
+ * @throws {TypeError} When two entries flatten to the same key, eg. the key
98
+ * `"user.role"` next to `{ user: { role } }`:
99
+ * `@asd14/m/flatten: expected 'user.role' to be 'Unique', got 'Duplicate'`
100
+ * @throws {RangeError} When the input is nested deeper than the stack allows
101
+ *
61
102
  * @example
62
103
  * flatten([1, [2], [3, [4]]])
63
104
  * // => [1, 2, 3, 4]
@@ -65,43 +106,60 @@ const _flatten = (input, level, separator)=>{
65
106
  * flatten({ a: { b: 1, c: { d: 2 } } })
66
107
  * // => { "a.b": 1, "a.c.d": 2 }
67
108
  *
68
- * flatten({ level: 1 }, [1, [2, [3]]])
109
+ * flatten(1, [1, [2, [3]]])
69
110
  * // => [1, 2, [3]]
70
111
  *
71
- * flatten({ separator: "__" }, { a: { b: 1 } })
112
+ * flatten("__", { a: { b: 1 } })
72
113
  * // => { a__b: 1 }
73
114
  *
115
+ * pipe(read("tags"), flatten(1))({
116
+ * tags: [[1], [2, [3]]]
117
+ * })
118
+ * // => [1, 2, [3]]
119
+ *
120
+ * pipe(read("meta"), flatten("/"))({
121
+ * meta: { a: { b: 1 } }
122
+ * })
123
+ * // => { "a/b": 1 }
124
+ *
74
125
  * flatten({ a: {}, b: { c: new Date(0) } })
75
126
  * // => { a: {}, "b.c": new Date(0) }
76
127
  *
77
- * pipe(
78
- * map(read("tags")),
79
- * flatten,
80
- * distinct
81
- * )([{ tags: ["a"] }, { tags: ["a", "b"] }])
82
- * // => ["a", "b"]
83
- *
84
128
  * @name flatten
85
129
  * @tag Array
86
130
  *
87
- * @see {@link unflatten}
131
+ * @see {@link unflatten} to rebuild the nested object from the flat keys
88
132
  */ const flatten = (...params)=>{
89
- // @signature (input)
133
+ const [first, input] = params;
134
+ // A number is the level, for an array. A string is the separator, for an
135
+ // object. Neither can be the input, so one argument of either is a pipe step
90
136
  if (params.length === 1) {
91
- return _flatten(params[0], Infinity, ".");
137
+ // @signature (level) => (input)
138
+ if (typeof first === "number") {
139
+ return (input)=>_flattenLevels(first, input);
140
+ }
141
+ // @signature (separator) => (input)
142
+ if (typeof first === "string") {
143
+ return (input)=>_flattenKeys(first, input);
144
+ }
145
+ // @signature (input)
146
+ return _flatten(first, Infinity, ".");
147
+ }
148
+ // @signature (level, input)
149
+ if (typeof first === "number") {
150
+ return _flattenLevels(first, input);
92
151
  }
93
- const options = params[0];
94
- if (!isPlainObject(options)) {
95
- throw new TypeError(`@asd14/m/flatten: expected 'options' to be 'Object', got '${type(options)}'`);
152
+ // @signature (separator, input)
153
+ if (typeof first === "string") {
154
+ return _flattenKeys(first, input);
96
155
  }
97
- const { level = Infinity, separator = "." } = options;
98
- if (typeof level !== "number") {
99
- throw new TypeError(`@asd14/m/flatten: expected 'level' to be 'Number', got '${type(level)}'`);
156
+ // Name the argument the input asks for, eg. for the options object of 10.x
157
+ if (Array.isArray(input)) {
158
+ throw new TypeError(`@asd14/m/flatten: expected 'level' to be 'Number', got '${type(first)}'`);
100
159
  }
101
- if (typeof separator !== "string") {
102
- throw new TypeError(`@asd14/m/flatten: expected 'separator' to be 'String', got '${type(separator)}'`);
160
+ if (isPlainObject(input)) {
161
+ throw new TypeError(`@asd14/m/flatten: expected 'separator' to be 'String', got '${type(first)}'`);
103
162
  }
104
- // @signature (options, input)
105
- return _flatten(params[1], level, separator);
163
+ return _flatten(input, Infinity, ".");
106
164
  };
107
165
  export { flatten };
@@ -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