@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
@@ -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 pickBest = (a, b)=>{
40
- if (a === undefined) {
41
- return b;
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
- if (b === undefined) {
44
- return a;
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
- return b.score > a.score ? b : a;
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
- * A row per query letter, a cell per text index. A cell contains the best
60
- * match of the query up to this letter, with this letter on this index
61
- */ let row = [];
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 previousRow = row;
65
- // The best cell of the previous row that leaves a gap before this index,
66
- // its score minus the penalty of that gap
67
- let gap;
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(let index = 0, length = row.length; index < length; index++){
110
- best = pickBest(best, row[index]);
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.indexes
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
@@ -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" },
@@ -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 key = String(fn(item));
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 {
@@ -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" },
@@ -32,6 +32,9 @@ type IndexByFn = {
32
32
  *
33
33
  * @returns {Object} Object of items, one for each key
34
34
  *
35
+ * @throws {TypeError} When `fn` returns neither a string nor a number, eg.
36
+ * `expected 'fn(input[1])' to be 'String' or 'Number', got 'Array'`
37
+ *
35
38
  * @example
36
39
  * indexBy(user => user.id, [
37
40
  * { id: 1, name: "alice" },
@@ -8,7 +8,13 @@ const _indexBy = (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
- _setOwn(result, String(fn(item)), item);
11
+ const key = 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 key !== "string" && typeof key !== "number") {
15
+ throw new TypeError(`@asd14/m/indexBy: expected 'fn(input[${i}])' to be 'String' or 'Number', got '${type(key)}'`);
16
+ }
17
+ _setOwn(result, String(key), item);
12
18
  }
13
19
  return result;
14
20
  };
@@ -29,6 +35,9 @@ const _indexBy = (fn, input)=>{
29
35
  *
30
36
  * @returns {Object} Object of items, one for each key
31
37
  *
38
+ * @throws {TypeError} When `fn` returns neither a string nor a number, eg.
39
+ * `expected 'fn(input[1])' to be 'String' or 'Number', got 'Array'`
40
+ *
32
41
  * @example
33
42
  * indexBy(user => user.id, [
34
43
  * { id: 1, name: "alice" },
@@ -59,7 +59,6 @@ export * from "./unite/unite.js";
59
59
  export * from "./update/with/update-with.js";
60
60
  export * from "./upsert/with/upsert-with.js";
61
61
  export * from "./zip-to-object/zip-to-object.js";
62
- export * from "./evolve/deep-by/evolve-deep-by.js";
63
62
  export * from "./evolve/evolve.js";
64
63
  export * from "./is-match/is-match.js";
65
64
  export * from "./keys/keys.js";
package/dist/src/index.js CHANGED
@@ -63,7 +63,6 @@ export * from "./update/with/update-with.js";
63
63
  export * from "./upsert/with/upsert-with.js";
64
64
  export * from "./zip-to-object/zip-to-object.js";
65
65
  // Object
66
- export * from "./evolve/deep-by/evolve-deep-by.js";
67
66
  export * from "./evolve/evolve.js";
68
67
  export * from "./is-match/is-match.js";
69
68
  export * from "./keys/keys.js";
@@ -9,6 +9,9 @@ type IntersectByFn = {
9
9
  * second array, where the first of each group of equal items wins. Order is
10
10
  * preserved - items appear in the order of the first array.
11
11
  *
12
+ * Compares each item with each kept item, so the time grows with the square
13
+ * of the input. To compare with SameValueZero, use `intersect`, which is linear.
14
+ *
12
15
  * Input is never mutated - always returns a new array.
13
16
  *
14
17
  * @param {Function} fn - `(item, other) => boolean`, true when equal. A pair
@@ -23,6 +23,9 @@ const _intersectBy = (fn, a, b)=>{
23
23
  * second array, where the first of each group of equal items wins. Order is
24
24
  * preserved - items appear in the order of the first array.
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 `intersect`, which is linear.
28
+ *
26
29
  * Input is never mutated - always returns a new array.
27
30
  *
28
31
  * @param {Function} fn - `(item, other) => boolean`, true when equal. A pair
@@ -3,11 +3,26 @@ type IsDeepEqualFn = {
3
3
  (left: unknown): (right: unknown) => boolean;
4
4
  };
5
5
  /**
6
- * Check two values for deep equality: arrays and typed arrays by items, `Map`
7
- * by entries, `Set` by keys, `RegExp` by source and flags, a `Date` or any
8
- * object with its own `valueOf` or `toString` by that result, other objects by
9
- * own enumerable keys. Objects of different constructors are never equal. A
10
- * React element skips its `_owner`, which is circular. Two `NaN` are equal.
6
+ * Check two values for deep equality: arrays and typed arrays by items, an
7
+ * `ArrayBuffer`, `SharedArrayBuffer` or `DataView` by bytes, `Map` by entries,
8
+ * `Set` by keys, `RegExp` by source and flags, a `Date` or any object with its
9
+ * own `valueOf` or `toString` by that result, other objects by own enumerable
10
+ * keys. Objects of different constructors are never equal. A React element
11
+ * skips its `_owner`, which is circular. Two `NaN` are equal.
12
+ *
13
+ * State a JS program cannot read is not compared, eg. the contents of a `Blob`,
14
+ * the value of a `Promise` or a `#private` field.
15
+ *
16
+ * To compare secrets, eg. two signatures, use `crypto.timingSafeEqual`:
17
+ * `isDeepEqual` returns at the first difference, so its time leaks where the
18
+ * values differ.
19
+ *
20
+ * It recurses, so the stack limits the depth: deeply nested input throws a
21
+ * `RangeError`. The limit depends on V8's stack size and on whether V8 has
22
+ * optimized the function yet. Run `src/is-deep-equal/bench/depth.ts` to find
23
+ * it on your machine, next to Node's, lodash's and underscore's. `JSON.parse`
24
+ * accepts any depth, so check the depth of untrusted input first, if it can
25
+ * be that deep.
11
26
  *
12
27
  * Input is never mutated.
13
28
  *
@@ -2,7 +2,21 @@
2
2
  * Ported from fast-deep-equal 3.1.3, its ES6 and React build, to TypeScript
3
3
  * https://github.com/epoberezkin/fast-deep-equal
4
4
  * MIT License, Copyright (c) 2017 Evgeny Poberezkin
5
- */ const _isDeepEqual = (left, right)=>{
5
+ */ // A browser defines SharedArrayBuffer only on a cross-origin isolated page
6
+ const _isBinary = (input)=>input instanceof ArrayBuffer || input instanceof DataView || typeof SharedArrayBuffer === "function" && input instanceof SharedArrayBuffer;
7
+ const _toBytes = (input)=>input instanceof DataView ? new Uint8Array(input.buffer, input.byteOffset, input.byteLength) : new Uint8Array(input);
8
+ const _isBytesEqual = (left, right)=>{
9
+ if (left.length !== right.length) {
10
+ return false;
11
+ }
12
+ for(let index = 0, length = left.length; index < length; index++){
13
+ if (left[index] !== right[index]) {
14
+ return false;
15
+ }
16
+ }
17
+ return true;
18
+ };
19
+ const _isDeepEqual = (left, right)=>{
6
20
  if (left === right) {
7
21
  return true;
8
22
  }
@@ -52,6 +66,12 @@
52
66
  }
53
67
  return true;
54
68
  }
69
+ // A buffer and a DataView have no keys and no length, so compare their
70
+ // bytes. fast-deep-equal 3.1.3 calls two different buffers equal, and loops
71
+ // forever on a DataView. The constructors match, so `right` has the same type
72
+ if (_isBinary(left)) {
73
+ return _isBytesEqual(_toBytes(left), _toBytes(right));
74
+ }
55
75
  if (ArrayBuffer.isView(left) && ArrayBuffer.isView(right)) {
56
76
  const leftView = left;
57
77
  const rightView = right;
@@ -83,7 +103,9 @@
83
103
  }
84
104
  const leftRecord = left;
85
105
  const rightRecord = right;
86
- const isReactElement = "$$typeof" in left;
106
+ // React marks an element with a symbol, which JSON cannot produce. A JSON
107
+ // object with a `$$typeof` key keeps its `_owner` in the comparison
108
+ const isReactElement = typeof left.$$typeof === "symbol";
87
109
  for(let index = 0, length = keys.length; index < length; index++){
88
110
  const key = keys[index];
89
111
  if (!Object.hasOwn(right, key)) {
@@ -100,11 +122,26 @@
100
122
  return true;
101
123
  };
102
124
  /**
103
- * Check two values for deep equality: arrays and typed arrays by items, `Map`
104
- * by entries, `Set` by keys, `RegExp` by source and flags, a `Date` or any
105
- * object with its own `valueOf` or `toString` by that result, other objects by
106
- * own enumerable keys. Objects of different constructors are never equal. A
107
- * React element skips its `_owner`, which is circular. Two `NaN` are equal.
125
+ * Check two values for deep equality: arrays and typed arrays by items, an
126
+ * `ArrayBuffer`, `SharedArrayBuffer` or `DataView` by bytes, `Map` by entries,
127
+ * `Set` by keys, `RegExp` by source and flags, a `Date` or any object with its
128
+ * own `valueOf` or `toString` by that result, other objects by own enumerable
129
+ * keys. Objects of different constructors are never equal. A React element
130
+ * skips its `_owner`, which is circular. Two `NaN` are equal.
131
+ *
132
+ * State a JS program cannot read is not compared, eg. the contents of a `Blob`,
133
+ * the value of a `Promise` or a `#private` field.
134
+ *
135
+ * To compare secrets, eg. two signatures, use `crypto.timingSafeEqual`:
136
+ * `isDeepEqual` returns at the first difference, so its time leaks where the
137
+ * values differ.
138
+ *
139
+ * It recurses, so the stack limits the depth: deeply nested input throws a
140
+ * `RangeError`. The limit depends on V8's stack size and on whether V8 has
141
+ * optimized the function yet. Run `src/is-deep-equal/bench/depth.ts` to find
142
+ * it on your machine, next to Node's, lodash's and underscore's. `JSON.parse`
143
+ * accepts any depth, so check the depth of untrusted input first, if it can
144
+ * be that deep.
108
145
  *
109
146
  * Input is never mutated.
110
147
  *
@@ -10,6 +10,10 @@ type IsMatchFn = {
10
10
  * a pipe of functions, never a value: match an array with a predicate. Reads
11
11
  * only the own keys of the input.
12
12
  *
13
+ * For each key of `match`, `isMatch` reads the input's value under that key,
14
+ * `undefined` when the input lacks it, and compares the two. So
15
+ * `{ ownerId: undefined }` matches an object that has no `ownerId`.
16
+ *
13
17
  * @param {Object} match - Subset of properties to test against
14
18
  * @param {Object} input - Object to test
15
19
  *
@@ -6,6 +6,10 @@ import { _buildMatch } from "../utils/build-match.js";
6
6
  * a pipe of functions, never a value: match an array with a predicate. Reads
7
7
  * only the own keys of the input.
8
8
  *
9
+ * For each key of `match`, `isMatch` reads the input's value under that key,
10
+ * `undefined` when the input lacks it, and compares the two. So
11
+ * `{ ownerId: undefined }` matches an object that has no `ownerId`.
12
+ *
9
13
  * @param {Object} match - Subset of properties to test against
10
14
  * @param {Object} input - Object to test
11
15
  *
@@ -12,9 +12,11 @@ const _buildURIRegExp = ()=>{
12
12
  const hexDigitOnly = `[${hexDigit}]`;
13
13
  const unreserved = `${alpha}${digit}-\\._~`;
14
14
  const subDelims = "!\\$&'\\(\\)\\*\\+,;=";
15
- const pctEncoded = `%${hexDigit}`;
16
- const pchar = `${unreserved}${pctEncoded}${subDelims}:@`;
17
- const pcharOnly = `[${pchar}]`;
15
+ // RFC 3986: pct-encoded = "%" HEXDIG HEXDIG, never a lone "%". It goes next
16
+ // to a character class as an alternative, since "%" is not in the class, so
17
+ // each character matches one way only and the regex cannot backtrack
18
+ const pctEncoded = `%${hexDigitOnly}{2}`;
19
+ const pcharOnly = `(?:[${unreserved}${subDelims}:@]|${pctEncoded})`;
18
20
  // dec-octet, with zero-padded addresses accepted
19
21
  const decOctet = `(?:0?0?${digitOnly}|0?[1-9]${digitOnly}|1${digitOnly}${digitOnly}` + `|2[0-4]${digitOnly}|25[0-5])`;
20
22
  const ipv4 = `(?:${decOctet}\\.){3}${decOctet}`;
@@ -32,10 +34,12 @@ const _buildURIRegExp = ()=>{
32
34
  `(?:(?:${h16}:){0,6}${h16})?::`
33
35
  ].join("|")})`;
34
36
  const ipFuture = `v${hexDigitOnly}+\\.[${unreserved}${subDelims}:]+`;
35
- const scheme = `[${alpha}][${alpha}${digit}+-\\.]*`;
36
- const userinfo = `[${unreserved}${pctEncoded}${subDelims}:]*`;
37
+ // `+.\-`, not `+-.`: inside a class, `+-.` is the range from + to ., which
38
+ // also covers the comma
39
+ const scheme = `[${alpha}][${alpha}${digit}+.\\-]*`;
40
+ const userinfo = `(?:[${unreserved}${subDelims}:]|${pctEncoded})*`;
37
41
  const ipLiteral = `\\[(?:${ipv6}|${ipFuture})\\]`;
38
- const regName = `[${unreserved}${pctEncoded}${subDelims}]{0,255}`;
42
+ const regName = `(?:[${unreserved}${subDelims}]|${pctEncoded}){0,255}`;
39
43
  const host = `(?:${ipLiteral}|${ipv4}|${regName})`;
40
44
  const authority = `(?:${userinfo}@)?${host}(?::${digitOnly}*)?`;
41
45
  const segment = `${pcharOnly}*`;
@@ -45,12 +49,11 @@ const _buildURIRegExp = ()=>{
45
49
  const pathRootless = `${segmentNz}${pathAbEmpty}`;
46
50
  const hierPart = `(?:(?:\\/\\/${authority}${pathAbEmpty})|${pathAbsolute}|${pathRootless})`;
47
51
  // The query ends at the fragment or at the end of the input
48
- const query = `[${pchar}\\/\\?]*(?=#|$)`;
49
- const fragment = `[${pchar}\\/\\?]*`;
52
+ const query = `(?:${pcharOnly}|[\\/\\?])*(?=#|$)`;
53
+ const fragment = `(?:${pcharOnly}|[\\/\\?])*`;
50
54
  return new RegExp(`^(?:${scheme}:${hierPart})(?:\\?${query})?(?:#${fragment})?$`);
51
55
  };
52
56
  const URI_REG_EXP = _buildURIRegExp();
53
- // --- Public function ---
54
57
  /**
55
58
  * Check that a string is a URI, as [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986)
56
59
  * defines it. A URI needs a scheme, `example.com` is not one. Takes one
@@ -10,7 +10,11 @@ type MergeFn = {
10
10
  };
11
11
  /**
12
12
  * Shallow-merge objects left-to-right. Right-most properties win. Every item
13
- * must be a plain object, and a `"__proto__"` key stays an own key.
13
+ * must be a plain object. Copies own string keys: a symbol key is left out.
14
+ *
15
+ * A `"__proto__"` key stays an own key, and the prototype never changes.
16
+ * `Object.assign` differs here: it assigns each key, so an own `"__proto__"`
17
+ * key from `JSON.parse` replaces the prototype of its target.
14
18
  *
15
19
  * Accepts variadic objects, an array of objects, or a single object
16
20
  * (curried, returns a function expecting the second object).
@@ -1,18 +1,24 @@
1
1
  import { isPlainObject } from "../is/is.js";
2
2
  import { type } from "../type/type.js";
3
+ import { _setOwn } from "../utils/set-own.js";
3
4
  const _merge = (objects)=>{
4
- let result = {};
5
+ // One result, written key by key: a spread of the result for each object
6
+ // copies it again each time, which grows with the square of the input
7
+ const result = {};
5
8
  for (const object of objects){
6
- result = {
7
- ...result,
8
- ...object
9
- };
9
+ for (const key of Object.keys(object)){
10
+ _setOwn(result, key, object[key]);
11
+ }
10
12
  }
11
13
  return result;
12
14
  };
13
15
  /**
14
16
  * Shallow-merge objects left-to-right. Right-most properties win. Every item
15
- * must be a plain object, and a `"__proto__"` key stays an own key.
17
+ * must be a plain object. Copies own string keys: a symbol key is left out.
18
+ *
19
+ * A `"__proto__"` key stays an own key, and the prototype never changes.
20
+ * `Object.assign` differs here: it assigns each key, so an own `"__proto__"`
21
+ * key from `JSON.parse` replaces the prototype of its target.
16
22
  *
17
23
  * Accepts variadic objects, an array of objects, or a single object
18
24
  * (curried, returns a function expecting the second object).
@@ -49,6 +49,13 @@ const _pick = (keys, input)=>{
49
49
  if (!Array.isArray(keys)) {
50
50
  throw new TypeError(`@asd14/m/pick: expected 'keys' to be 'Array', got '${type(keys)}'`);
51
51
  }
52
+ // A key that is not a string passes the check of _setOwn, then the
53
+ // assignment turns it into one, eg. ["__proto__"] into "__proto__"
54
+ for(let i = 0, length = keys.length; i < length; i++){
55
+ if (typeof keys[i] !== "string") {
56
+ throw new TypeError(`@asd14/m/pick: expected 'keys[${i}]' to be 'String', got '${type(keys[i])}'`);
57
+ }
58
+ }
52
59
  // @signature (keys) => (input)
53
60
  if (params.length === 1) {
54
61
  return (input)=>_pick(keys, input);
@@ -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
  *