@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.
Files changed (67) 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/drop/drop.d.ts +38 -0
  7. package/dist/src/drop/drop.js +56 -0
  8. package/dist/src/escape/escape.js +6 -1
  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 +7 -0
  12. package/dist/src/flatten/flatten.js +14 -1
  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 +19 -7
  16. package/dist/src/group/group-by.js +20 -2
  17. package/dist/src/index-by/index-by.d.ts +70 -0
  18. package/dist/src/index-by/index-by.js +82 -0
  19. package/dist/src/index.d.ts +12 -1
  20. package/dist/src/index.js +12 -9
  21. package/dist/src/intersect/by/intersect-by.d.ts +48 -0
  22. package/dist/src/intersect/by/intersect-by.js +75 -0
  23. package/dist/src/intersect/intersect.d.ts +42 -0
  24. package/dist/src/intersect/intersect.js +63 -0
  25. package/dist/src/is-deep-equal/is-deep-equal.d.ts +20 -5
  26. package/dist/src/is-deep-equal/is-deep-equal.js +44 -7
  27. package/dist/src/is-uri/is-uri.js +12 -9
  28. package/dist/src/max/by/max-by.d.ts +52 -0
  29. package/dist/src/max/by/max-by.js +69 -0
  30. package/dist/src/max/max.d.ts +34 -0
  31. package/dist/src/max/max.js +49 -0
  32. package/dist/src/merge/merge.d.ts +5 -1
  33. package/dist/src/merge/merge.js +12 -6
  34. package/dist/src/min/by/min-by.d.ts +52 -0
  35. package/dist/src/min/by/min-by.js +69 -0
  36. package/dist/src/min/min.d.ts +34 -0
  37. package/dist/src/min/min.js +49 -0
  38. package/dist/src/pick/pick.js +7 -0
  39. package/dist/src/read/read.d.ts +1 -0
  40. package/dist/src/read/read.js +1 -0
  41. package/dist/src/take/last/take-last.d.ts +38 -0
  42. package/dist/src/take/last/take-last.js +56 -0
  43. package/dist/src/take/take.d.ts +38 -0
  44. package/dist/src/take/take.js +56 -0
  45. package/dist/src/throttle/throttle.d.ts +11 -1
  46. package/dist/src/throttle/throttle.js +49 -43
  47. package/dist/src/unite/by/unite-by.d.ts +3 -0
  48. package/dist/src/unite/by/unite-by.js +3 -0
  49. package/dist/src/update/update.d.ts +2 -2
  50. package/dist/src/utils/build-patch.js +3 -1
  51. package/dist/src/utils/parse-timer-options.d.ts +22 -0
  52. package/dist/src/utils/parse-timer-options.js +44 -0
  53. package/dist/src/utils/set-own.d.ts +5 -4
  54. package/dist/src/utils/set-own.js +6 -5
  55. package/dist/src/values/values.d.ts +42 -0
  56. package/dist/src/values/values.js +46 -0
  57. package/dist/src/write/write.d.ts +53 -0
  58. package/dist/src/write/write.js +104 -0
  59. package/dist/src/zip-to-object/zip-to-object.js +7 -0
  60. package/dist/types/object.d.ts +53 -4
  61. package/docs/SPEC.md +8 -7
  62. package/docs/how-to/prototype-pollution-tests.md +156 -0
  63. package/docs/how-to/tape-runtime-tests.md +30 -21
  64. package/docs/how-to/tstyche-type-tests.md +29 -14
  65. package/package.json +8 -5
  66. package/dist/src/evolve/deep-by/evolve-deep-by.d.ts +0 -65
  67. package/dist/src/evolve/deep-by/evolve-deep-by.js +0 -90
@@ -0,0 +1,56 @@
1
+ import { type } from "../type/type.js";
2
+ const _take = (count, input)=>{
3
+ if (!Array.isArray(input)) {
4
+ throw new TypeError(`@asd14/m/take: expected 'input' to be 'Array', got '${type(input)}'`);
5
+ }
6
+ return input.slice(0, count);
7
+ };
8
+ /**
9
+ * Take elements from the start of an array. When called with only an array,
10
+ * takes 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 the first `count` elements
18
+ *
19
+ * @example
20
+ * take([1, 2, 3])
21
+ * // => [1]
22
+ *
23
+ * take(2, [1, 2, 3])
24
+ * // => [1, 2]
25
+ *
26
+ * take(2)([1, 2, 3])
27
+ * // => [1, 2]
28
+ *
29
+ * pipe(take(2), map(read("id")))([{ id: 1 }, { id: 2 }, { id: 3 }])
30
+ * // => [1, 2]
31
+ *
32
+ * @name take
33
+ * @tag Array
34
+ *
35
+ * @see {@link first}
36
+ * @see {@link takeLast}
37
+ */ const take = (...params)=>{
38
+ // @signature (input)
39
+ if (Array.isArray(params[0])) {
40
+ return _take(1, params[0]);
41
+ }
42
+ const count = params[0];
43
+ if (typeof count !== "number") {
44
+ throw new TypeError(`@asd14/m/take: expected 'count' to be 'Number', got '${type(count)}'`);
45
+ }
46
+ if (!Number.isInteger(count) || count < 0) {
47
+ throw new TypeError(`@asd14/m/take: expected 'count' to be 'NonNegativeInteger', got '${String(count)}'`);
48
+ }
49
+ // @signature (count, input)
50
+ if (params.length === 2) {
51
+ return _take(count, params[1]);
52
+ }
53
+ // @signature (count) => (input)
54
+ return (input)=>_take(count, input);
55
+ };
56
+ export { take };
@@ -1,6 +1,8 @@
1
1
  type ThrottleOptions = {
2
- /** Milliseconds between runs of `fn`, default `50` */
2
+ /** Milliseconds between runs of `fn`, at most 2,147,483,647, default `50` */
3
3
  wait?: number;
4
+ /** Drops the call waiting for the window end when aborted, and makes later calls do nothing */
5
+ signal?: AbortSignal;
4
6
  /** Run `fn` once more at the end of the window for a dropped call, default `false` */
5
7
  hasLastCall?: boolean;
6
8
  };
@@ -36,6 +38,14 @@ type ThrottleFn = {
36
38
  * onScroll(2)
37
39
  * // update(1) runs now, update(2) runs 100 ms later
38
40
  *
41
+ * // Abort with a signal: the call waiting for the window end never runs, and
42
+ * // later calls do nothing. The same signal removes the listener
43
+ * const controller = new AbortController()
44
+ * const onResize = throttle({ wait: 100, signal: controller.signal }, layout)
45
+ *
46
+ * window.addEventListener("resize", onResize, { signal: controller.signal })
47
+ * controller.abort()
48
+ *
39
49
  * @name throttle
40
50
  * @tag Function
41
51
  *
@@ -1,25 +1,41 @@
1
- import { isPlainObject } from "../is/is.js";
2
1
  import { type } from "../type/type.js";
3
- const _throttle = (fn, wait, hasLastCall)=>{
4
- let lastExecution = Date.now() - wait;
5
- let timer;
2
+ import { _parseTimerOptions } from "../utils/parse-timer-options.js";
3
+ const _throttle = (fn, wait, hasLastCall, signal)=>{
4
+ // The window opens when fn runs, and closes when its timer fires. No clock
5
+ // is read, so a wall clock that steps back cannot stretch the window
6
+ let windowTimer;
7
+ // The last call the window dropped, run when the window closes
8
+ let lastParams;
9
+ const run = (params)=>{
10
+ fn(...params);
11
+ // With no wait, every call runs: a 0 ms window would still drop the
12
+ // calls made before the next task
13
+ if (wait > 0) {
14
+ windowTimer = setTimeout(()=>{
15
+ windowTimer = undefined;
16
+ if (lastParams) {
17
+ const params = lastParams;
18
+ lastParams = undefined;
19
+ run(params);
20
+ }
21
+ }, wait);
22
+ }
23
+ };
24
+ signal?.addEventListener("abort", ()=>{
25
+ clearTimeout(windowTimer);
26
+ windowTimer = undefined;
27
+ lastParams = undefined;
28
+ }, {
29
+ once: true
30
+ });
6
31
  return (...params)=>{
7
- const now = Date.now();
8
- if (lastExecution + wait <= now) {
9
- clearTimeout(timer);
10
- timer = undefined;
11
- lastExecution = now;
12
- fn(...params);
32
+ if (signal?.aborted) {
13
33
  return;
14
34
  }
15
- // The window dropped this call: run it at the end of the window
16
- if (hasLastCall) {
17
- clearTimeout(timer);
18
- timer = setTimeout(()=>{
19
- timer = undefined;
20
- lastExecution = Date.now();
21
- fn(...params);
22
- }, lastExecution + wait - now);
35
+ if (windowTimer === undefined) {
36
+ run(params);
37
+ } else if (hasLastCall) {
38
+ lastParams = params;
23
39
  }
24
40
  };
25
41
  };
@@ -51,40 +67,30 @@ const _throttle = (fn, wait, hasLastCall)=>{
51
67
  * onScroll(2)
52
68
  * // update(1) runs now, update(2) runs 100 ms later
53
69
  *
70
+ * // Abort with a signal: the call waiting for the window end never runs, and
71
+ * // later calls do nothing. The same signal removes the listener
72
+ * const controller = new AbortController()
73
+ * const onResize = throttle({ wait: 100, signal: controller.signal }, layout)
74
+ *
75
+ * window.addEventListener("resize", onResize, { signal: controller.signal })
76
+ * controller.abort()
77
+ *
54
78
  * @name throttle
55
79
  * @tag Function
56
80
  *
57
81
  * @see {@link debounce}
58
82
  */ const throttle = (...params)=>{
59
83
  const fn = params[params.length - 1];
60
- let wait = 50;
61
- let hasLastCall = false;
62
- if (params.length > 1) {
63
- const options = params[0];
64
- if (!isPlainObject(options)) {
65
- throw new TypeError(`@asd14/m/throttle: expected 'options' to be 'Object', got '${type(options)}'`);
66
- }
67
- const optionWait = options["wait"];
68
- const optionHasLastCall = options["hasLastCall"];
69
- if (optionWait !== undefined) {
70
- if (typeof optionWait !== "number") {
71
- throw new TypeError(`@asd14/m/throttle: expected 'wait' to be 'Number', got '${type(optionWait)}'`);
72
- }
73
- if (!(optionWait >= 0)) {
74
- throw new TypeError(`@asd14/m/throttle: expected 'wait' to be 'NonNegative', got '${String(optionWait)}'`);
75
- }
76
- wait = optionWait;
77
- }
78
- if (optionHasLastCall !== undefined) {
79
- if (typeof optionHasLastCall !== "boolean") {
80
- throw new TypeError(`@asd14/m/throttle: expected 'hasLastCall' to be 'Boolean', got '${type(optionHasLastCall)}'`);
81
- }
82
- hasLastCall = optionHasLastCall;
83
- }
84
+ const { options, wait, signal } = _parseTimerOptions(params.length > 1 ? params[0] : undefined, {
85
+ fnName: "throttle"
86
+ });
87
+ const { hasLastCall = false } = options;
88
+ if (typeof hasLastCall !== "boolean") {
89
+ throw new TypeError(`@asd14/m/throttle: expected 'hasLastCall' to be 'Boolean', got '${type(hasLastCall)}'`);
84
90
  }
85
91
  if (typeof fn !== "function") {
86
92
  throw new TypeError(`@asd14/m/throttle: expected 'fn' to be 'Function', got '${type(fn)}'`);
87
93
  }
88
- return _throttle(fn, wait, hasLastCall);
94
+ return _throttle(fn, wait, hasLastCall, signal);
89
95
  };
90
96
  export { throttle };
@@ -8,6 +8,9 @@ type UniteByFn = {
8
8
  * array of the items of both arrays, where the first of each group of equal
9
9
  * items wins. Order is preserved - items from the first array appear first.
10
10
  *
11
+ * Compares each item with each kept item, so the time grows with the square
12
+ * of the input. To compare with SameValueZero, use `unite`, which is linear.
13
+ *
11
14
  * Input is never mutated - always returns a new array.
12
15
  *
13
16
  * @param {Function} fn - `(newItem, keptItem) => boolean`, true when equal
@@ -15,6 +15,9 @@ const _uniteBy = (fn, a, b)=>{
15
15
  * array of the items of both arrays, where the first of each group of equal
16
16
  * items wins. Order is preserved - items from the first array appear first.
17
17
  *
18
+ * Compares each item with each kept item, so the time grows with the square
19
+ * of the input. To compare with SameValueZero, use `unite`, which is linear.
20
+ *
18
21
  * Input is never mutated - always returns a new array.
19
22
  *
20
23
  * @param {Function} fn - `(newItem, keptItem) => boolean`, true when equal
@@ -1,5 +1,5 @@
1
- import type { PlainObject } from "../../types/object.js";
2
- import type { Patcher } from "../../types/object.patcher.js";
1
+ import type { Patcher } from "../../types/object.patcher.ts";
2
+ import type { PlainObject } from "../../types/object.ts";
3
3
  type UpdateFn = {
4
4
  <T extends PlainObject>(patcher: Patcher<T>, input: T): T;
5
5
  <T extends PlainObject>(patcher: Patcher<T>): <U extends T>(input: U) => U;
@@ -51,7 +51,9 @@ import { type } from "../type/type.js";
51
51
  if (isTransformOnly && !Object.hasOwn(input, key)) {
52
52
  continue;
53
53
  }
54
- _setOwn(result, key, isFunction ? value(input[key], input) : value);
54
+ _setOwn(result, key, // An own value only: a key the input lacks, eg. toString, gives
55
+ // undefined, not the value Object.prototype has
56
+ isFunction ? value(Object.hasOwn(input, key) ? input[key] : undefined, input) : value);
55
57
  }
56
58
  return result;
57
59
  };
@@ -0,0 +1,22 @@
1
+ import type { PlainObject } from "../../types/object.js";
2
+ type TimerOptions = {
3
+ /** The options object, checked to be plain, for the options of one caller */
4
+ options: PlainObject;
5
+ wait: number;
6
+ signal: AbortSignal | undefined;
7
+ };
8
+ /**
9
+ * Check the options that `debounce` and `throttle` share: `wait`, a delay a
10
+ * timer can hold, and `signal`, an `AbortSignal`.
11
+ *
12
+ * @example
13
+ * _parseTimerOptions({ wait: 300 }, { fnName: "debounce" })
14
+ * // => { options: { wait: 300 }, wait: 300, signal: undefined }
15
+ *
16
+ * _parseTimerOptions({ wait: Infinity }, { fnName: "debounce" })
17
+ * // throws "@asd14/m/debounce: expected 'wait' to be 'TimerDelay', got 'Infinity'"
18
+ */
19
+ declare const _parseTimerOptions: (options: unknown, { fnName }: {
20
+ fnName: string;
21
+ }) => TimerOptions;
22
+ export { _parseTimerOptions };
@@ -0,0 +1,44 @@
1
+ import { isPlainObject } from "../is/is.js";
2
+ import { type } from "../type/type.js";
3
+ // A timer stores its delay in 32 bits. Node and browsers run a larger delay,
4
+ // or Infinity, after 1 ms
5
+ const MAX_TIMER_DELAY = 2_147_483_647;
6
+ const DEFAULT_WAIT = 50;
7
+ /**
8
+ * Check the options that `debounce` and `throttle` share: `wait`, a delay a
9
+ * timer can hold, and `signal`, an `AbortSignal`.
10
+ *
11
+ * @example
12
+ * _parseTimerOptions({ wait: 300 }, { fnName: "debounce" })
13
+ * // => { options: { wait: 300 }, wait: 300, signal: undefined }
14
+ *
15
+ * _parseTimerOptions({ wait: Infinity }, { fnName: "debounce" })
16
+ * // throws "@asd14/m/debounce: expected 'wait' to be 'TimerDelay', got 'Infinity'"
17
+ */ const _parseTimerOptions = (options, { fnName })=>{
18
+ if (options === undefined) {
19
+ return {
20
+ options: {},
21
+ wait: DEFAULT_WAIT,
22
+ signal: undefined
23
+ };
24
+ }
25
+ if (!isPlainObject(options)) {
26
+ throw new TypeError(`@asd14/m/${fnName}: expected 'options' to be 'Object', got '${type(options)}'`);
27
+ }
28
+ const { wait = DEFAULT_WAIT, signal } = options;
29
+ if (typeof wait !== "number") {
30
+ throw new TypeError(`@asd14/m/${fnName}: expected 'wait' to be 'Number', got '${type(wait)}'`);
31
+ }
32
+ if (!(wait >= 0 && wait <= MAX_TIMER_DELAY)) {
33
+ throw new TypeError(`@asd14/m/${fnName}: expected 'wait' to be 'TimerDelay', got '${String(wait)}'`);
34
+ }
35
+ if (signal !== undefined && !(signal instanceof AbortSignal)) {
36
+ throw new TypeError(`@asd14/m/${fnName}: expected 'signal' to be 'AbortSignal', got '${type(signal)}'`);
37
+ }
38
+ return {
39
+ options,
40
+ wait,
41
+ signal
42
+ };
43
+ };
44
+ export { _parseTimerOptions };
@@ -2,10 +2,11 @@ import type { PlainObject } from "../../types/object.js";
2
2
  /**
3
3
  * Set an own key on an object that the caller is building.
4
4
  *
5
- * A plain assignment of `__proto__` calls the setter of `Object.prototype` and
6
- * changes the prototype in place of setting a key. `__proto__` is the one
7
- * accessor on `Object.prototype`, so every other key keeps the assignment,
8
- * which builds an object about 11 times faster than `Object.defineProperty`.
5
+ * A plain assignment of a key that the prototype chain has, eg. `__proto__` or
6
+ * `constructor`, reaches the inherited property: it calls the `__proto__`
7
+ * setter, and it throws when the prototype is frozen. Such a key gets
8
+ * `Object.defineProperty`. Every other key keeps the assignment, which builds
9
+ * an object about 11 times faster.
9
10
  *
10
11
  * Writes into `target`. Pass only an object you created.
11
12
  *
@@ -1,10 +1,11 @@
1
1
  /**
2
2
  * Set an own key on an object that the caller is building.
3
3
  *
4
- * A plain assignment of `__proto__` calls the setter of `Object.prototype` and
5
- * changes the prototype in place of setting a key. `__proto__` is the one
6
- * accessor on `Object.prototype`, so every other key keeps the assignment,
7
- * which builds an object about 11 times faster than `Object.defineProperty`.
4
+ * A plain assignment of a key that the prototype chain has, eg. `__proto__` or
5
+ * `constructor`, reaches the inherited property: it calls the `__proto__`
6
+ * setter, and it throws when the prototype is frozen. Such a key gets
7
+ * `Object.defineProperty`. Every other key keeps the assignment, which builds
8
+ * an object about 11 times faster.
8
9
  *
9
10
  * Writes into `target`. Pass only an object you created.
10
11
  *
@@ -15,7 +16,7 @@
15
16
  * Object.keys(result)
16
17
  * // => ["__proto__"]
17
18
  */ const _setOwn = (target, key, value)=>{
18
- if (key === "__proto__") {
19
+ if (key in target && !Object.hasOwn(target, key)) {
19
20
  Object.defineProperty(target, key, {
20
21
  value,
21
22
  enumerable: true,
@@ -0,0 +1,42 @@
1
+ type ValuesFn = {
2
+ <T>(input: readonly T[]): T[];
3
+ <T extends Record<string, unknown>>(input: T): T[keyof T][];
4
+ };
5
+ /**
6
+ * Get list of own enumerable property values.
7
+ *
8
+ * Returns the items of an array, the values of a plain object in key order.
9
+ * Any other object throws, eg. a `Map`: read its values with
10
+ * `[...map.values()]`.
11
+ *
12
+ * @param {Array|Object} input - Array or Object to extract values from
13
+ *
14
+ * @returns {Array} List of values
15
+ *
16
+ * @throws {TypeError} If input is not an Array or Object
17
+ *
18
+ * @example
19
+ * values(["lorem", "ipsum"])
20
+ * // => ["lorem", "ipsum"]
21
+ *
22
+ * values({ foo: "bar", lorem: "ipsum" })
23
+ * // => ["bar", "ipsum"]
24
+ *
25
+ * values(new Map([["foo", "bar"]]))
26
+ * // throws "@asd14/m/values: expected 'input' to be 'Array' or 'Object', got 'Map'"
27
+ *
28
+ * // In a pipe - sum the values of an object
29
+ * pipe(
30
+ * values,
31
+ * sum
32
+ * )({ a: 1, b: 2, c: 3 })
33
+ * // => 6
34
+ *
35
+ * @name values
36
+ * @tag Object
37
+ *
38
+ * @see {@link keys}
39
+ */
40
+ declare const values: ValuesFn;
41
+ export { values };
42
+ export type { ValuesFn };
@@ -0,0 +1,46 @@
1
+ import { isPlainObject } from "../is/is.js";
2
+ import { type } from "../type/type.js";
3
+ /**
4
+ * Get list of own enumerable property values.
5
+ *
6
+ * Returns the items of an array, the values of a plain object in key order.
7
+ * Any other object throws, eg. a `Map`: read its values with
8
+ * `[...map.values()]`.
9
+ *
10
+ * @param {Array|Object} input - Array or Object to extract values from
11
+ *
12
+ * @returns {Array} List of values
13
+ *
14
+ * @throws {TypeError} If input is not an Array or Object
15
+ *
16
+ * @example
17
+ * values(["lorem", "ipsum"])
18
+ * // => ["lorem", "ipsum"]
19
+ *
20
+ * values({ foo: "bar", lorem: "ipsum" })
21
+ * // => ["bar", "ipsum"]
22
+ *
23
+ * values(new Map([["foo", "bar"]]))
24
+ * // throws "@asd14/m/values: expected 'input' to be 'Array' or 'Object', got 'Map'"
25
+ *
26
+ * // In a pipe - sum the values of an object
27
+ * pipe(
28
+ * values,
29
+ * sum
30
+ * )({ a: 1, b: 2, c: 3 })
31
+ * // => 6
32
+ *
33
+ * @name values
34
+ * @tag Object
35
+ *
36
+ * @see {@link keys}
37
+ */ const values = (input)=>{
38
+ // A Map, a Set or a class instance throws: `[]` for a Map would look like an
39
+ // answer. Read a Map's values with `[...map.values()]`
40
+ if (!Array.isArray(input) && !isPlainObject(input)) {
41
+ throw new TypeError(`@asd14/m/values: expected 'input' to be 'Array' or 'Object', got '${type(input)}'`);
42
+ }
43
+ const result = Object.values(input);
44
+ return result;
45
+ };
46
+ export { values };
@@ -0,0 +1,53 @@
1
+ import type { DeepWrite } from "../../types/object.js";
2
+ type WritePath = readonly [string | number, ...(string | number)[]];
3
+ type WriteValue = string | number | boolean | bigint | symbol | object | null | undefined;
4
+ type WriteFn = {
5
+ <I extends object, const P extends WritePath, V extends WriteValue>(path: P, value: V, input: I): DeepWrite<I, P, V>;
6
+ <const P extends WritePath, V extends WriteValue>(path: P, value: V): <I extends object>(input: I) => DeepWrite<I, P, V>;
7
+ <I extends object, K extends string, V extends WriteValue>(path: K, value: V, input: I): DeepWrite<I, [K], V>;
8
+ <K extends string, V extends WriteValue>(path: K, value: V): <I extends object>(input: I) => DeepWrite<I, [K], V>;
9
+ };
10
+ /**
11
+ * Write a value at a key or a deep path. Creates each missing step: an array
12
+ * for an integer segment, a plain object for any other. Copies only the
13
+ * objects along the path, every other branch keeps its reference.
14
+ *
15
+ * Input is never mutated, always returns a new object or array.
16
+ *
17
+ * @param {string|Array} path - Key, or array of keys and indexes for deep access
18
+ * @param {unknown} value - Value to write, a function included
19
+ * @param {Object|Array} input - Object or array to write into
20
+ *
21
+ * @returns {Object|Array} A copy of `input` with `value` at `path`
22
+ *
23
+ * @throws {TypeError} When a value on the path is neither a plain object nor
24
+ * an array, eg. `expected 'input.a' to be 'Object' or 'Array', got 'Number'`
25
+ *
26
+ * @example
27
+ * write("name", "bob", { id: 1, name: "alice" })
28
+ * // => { id: 1, name: "bob" }
29
+ *
30
+ * write("name", "bob")({ id: 1 })
31
+ * // => { id: 1, name: "bob" }
32
+ *
33
+ * write(["a", "b"], 2, { a: { b: 1, c: 3 } })
34
+ * // => { a: { b: 2, c: 3 } }
35
+ *
36
+ * write(["tags", 0], "x")({})
37
+ * // => { tags: ["x"] }
38
+ *
39
+ * pipe(
40
+ * write(["user", "name"], "bob"),
41
+ * read(["user", "name"])
42
+ * )({ user: { name: "alice" } })
43
+ * // => "bob"
44
+ *
45
+ * @name write
46
+ * @tag Object
47
+ *
48
+ * @see {@link read}
49
+ * @see {@link update}
50
+ */
51
+ declare const write: WriteFn;
52
+ export { write };
53
+ export type { WriteFn };
@@ -0,0 +1,104 @@
1
+ import { isPlainObject } from "../is/is.js";
2
+ import { type } from "../type/type.js";
3
+ import { _setOwn } from "../utils/set-own.js";
4
+ const isIndex = (segment)=>typeof segment === "number" && Number.isInteger(segment) && segment >= 0;
5
+ const shallowCopy = (container)=>Array.isArray(container) ? [
6
+ ...container
7
+ ] : {
8
+ ...container
9
+ };
10
+ const _write = (segments, value, input)=>{
11
+ if (!isPlainObject(input) && !Array.isArray(input)) {
12
+ throw new TypeError(`@asd14/m/write: expected 'input' to be 'Object' or 'Array', got '${type(input)}'`);
13
+ }
14
+ const result = shallowCopy(input);
15
+ const lastIndex = segments.length - 1;
16
+ let node = result;
17
+ let pathName = "input";
18
+ for(let i = 0; i < lastIndex; i++){
19
+ const segment = segments[i];
20
+ const key = String(segment);
21
+ const child = Object.hasOwn(node, key) ? node[key] : undefined;
22
+ let copy;
23
+ pathName += isIndex(segment) ? `[${key}]` : `.${key}`;
24
+ if (child === undefined) {
25
+ copy = isIndex(segments[i + 1]) ? [] : {};
26
+ } else if (isPlainObject(child) || Array.isArray(child)) {
27
+ copy = shallowCopy(child);
28
+ } else {
29
+ throw new TypeError(`@asd14/m/write: expected '${pathName}' to be 'Object' or 'Array', got '${type(child)}'`);
30
+ }
31
+ _setOwn(node, key, copy);
32
+ node = copy;
33
+ }
34
+ _setOwn(node, String(segments[lastIndex]), value);
35
+ return result;
36
+ };
37
+ /**
38
+ * Write a value at a key or a deep path. Creates each missing step: an array
39
+ * for an integer segment, a plain object for any other. Copies only the
40
+ * objects along the path, every other branch keeps its reference.
41
+ *
42
+ * Input is never mutated, always returns a new object or array.
43
+ *
44
+ * @param {string|Array} path - Key, or array of keys and indexes for deep access
45
+ * @param {unknown} value - Value to write, a function included
46
+ * @param {Object|Array} input - Object or array to write into
47
+ *
48
+ * @returns {Object|Array} A copy of `input` with `value` at `path`
49
+ *
50
+ * @throws {TypeError} When a value on the path is neither a plain object nor
51
+ * an array, eg. `expected 'input.a' to be 'Object' or 'Array', got 'Number'`
52
+ *
53
+ * @example
54
+ * write("name", "bob", { id: 1, name: "alice" })
55
+ * // => { id: 1, name: "bob" }
56
+ *
57
+ * write("name", "bob")({ id: 1 })
58
+ * // => { id: 1, name: "bob" }
59
+ *
60
+ * write(["a", "b"], 2, { a: { b: 1, c: 3 } })
61
+ * // => { a: { b: 2, c: 3 } }
62
+ *
63
+ * write(["tags", 0], "x")({})
64
+ * // => { tags: ["x"] }
65
+ *
66
+ * pipe(
67
+ * write(["user", "name"], "bob"),
68
+ * read(["user", "name"])
69
+ * )({ user: { name: "alice" } })
70
+ * // => "bob"
71
+ *
72
+ * @name write
73
+ * @tag Object
74
+ *
75
+ * @see {@link read}
76
+ * @see {@link update}
77
+ */ const write = (...params)=>{
78
+ const path = params[0];
79
+ if (typeof path !== "string" && !Array.isArray(path)) {
80
+ throw new TypeError(`@asd14/m/write: expected 'path' to be 'String' or 'Array', got '${type(path)}'`);
81
+ }
82
+ if (Array.isArray(path) && path.length === 0) {
83
+ throw new TypeError("@asd14/m/write: expected 'path' to be 'NonEmpty', got 'Empty'");
84
+ }
85
+ if (params.length === 1) {
86
+ throw new TypeError("@asd14/m/write: expected 'value' to be 'Any', got 'Missing'");
87
+ }
88
+ const segments = Array.isArray(path) ? path : [
89
+ path
90
+ ];
91
+ for(let i = 0, length = segments.length; i < length; i++){
92
+ const segment = segments[i];
93
+ if (typeof segment !== "string" && typeof segment !== "number") {
94
+ throw new TypeError(`@asd14/m/write: expected 'path[${i}]' to be 'String' or 'Number', got '${type(segment)}'`);
95
+ }
96
+ }
97
+ // @signature (path, value) => (input)
98
+ if (params.length === 2) {
99
+ return (input)=>_write(segments, params[1], input);
100
+ }
101
+ // @signature (path, value, input)
102
+ return _write(segments, params[1], params[2]);
103
+ };
104
+ export { write };
@@ -48,6 +48,13 @@ const _zipToObject = (keys, values)=>{
48
48
  if (!Array.isArray(keys)) {
49
49
  throw new TypeError(`@asd14/m/zipToObject: expected 'keys' to be 'Array', got '${type(keys)}'`);
50
50
  }
51
+ // A key that is not a string passes the check of _setOwn, then the
52
+ // assignment turns it into one, eg. ["__proto__"] into "__proto__"
53
+ for(let i = 0, length = keys.length; i < length; i++){
54
+ if (typeof keys[i] !== "string") {
55
+ throw new TypeError(`@asd14/m/zipToObject: expected 'keys[${i}]' to be 'String', got '${type(keys[i])}'`);
56
+ }
57
+ }
51
58
  // @signature (keys) => (values)
52
59
  if (params.length === 1) {
53
60
  return (values)=>_zipToObject(keys, values);