@ocavue/utils 0.9.0 → 1.1.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/index.d.ts CHANGED
@@ -3,6 +3,26 @@
3
3
  * Checks if the given value is an object.
4
4
  */
5
5
  declare function isObject(value: unknown): value is Record<string | symbol | number, unknown>;
6
+ /**
7
+ * Checks if the given value is a Map.
8
+ */
9
+ declare function isMap(value: unknown): value is Map<unknown, unknown>;
10
+ /**
11
+ * Checks if the given value is a Set.
12
+ */
13
+ declare function isSet(value: unknown): value is Set<unknown>;
14
+ //#endregion
15
+ //#region src/default-map.d.ts
16
+ /**
17
+ * A map that automatically creates values for missing keys using a factory function.
18
+ *
19
+ * Similar to Python's [defaultdict](https://docs.python.org/3.13/library/collections.html#collections.defaultdict).
20
+ */
21
+ declare class DefaultMap<K, V> extends Map<K, V> {
22
+ private readonly defaultFactory;
23
+ constructor(defaultFactory: () => V, iterable?: Iterable<readonly [K, V]>);
24
+ get(key: K): V;
25
+ }
6
26
  //#endregion
7
27
  //#region src/dom.d.ts
8
28
  /**
@@ -78,6 +98,28 @@ declare function formatBytes(bytes: number): string;
78
98
  */
79
99
  declare function getId(): number;
80
100
  //#endregion
101
+ //#region src/is-deep-equal.d.ts
102
+ /**
103
+ * Whether two values are deeply equal.
104
+ */
105
+ declare function isDeepEqual(a: unknown, b: unknown): boolean;
106
+ //#endregion
107
+ //#region src/map-group-by.d.ts
108
+ /**
109
+ * A polyfill for the `Map.groupBy` static method.
110
+ *
111
+ * @public
112
+ */
113
+ declare const mapGroupBy: <K, T>(items: Iterable<T>, keySelector: (item: T, index: number) => K) => Map<K, T[]>;
114
+ //#endregion
115
+ //#region src/object-group-by.d.ts
116
+ /**
117
+ * A polyfill for the `Object.groupBy` static method.
118
+ *
119
+ * @public
120
+ */
121
+ declare const objectGroupBy: <K extends PropertyKey, T>(items: Iterable<T>, keySelector: (item: T, index: number) => K) => Partial<Record<K, T[]>>;
122
+ //#endregion
81
123
  //#region src/once.d.ts
82
124
  /**
83
125
  * Creates a function that will only execute the provided function once.
@@ -100,17 +142,5 @@ declare function once<T>(fn: () => T): () => T;
100
142
  */
101
143
  declare function sleep(ms: number): Promise<void>;
102
144
  //#endregion
103
- //#region src/default-map.d.ts
104
- /**
105
- * A map that automatically creates values for missing keys using a factory function.
106
- *
107
- * Similar to Python's [defaultdict](https://docs.python.org/3.13/library/collections.html#collections.defaultdict).
108
- */
109
- declare class DefaultMap<K, V> extends Map<K, V> {
110
- private readonly defaultFactory;
111
- constructor(defaultFactory: () => V, iterable?: Iterable<readonly [K, V]>);
112
- get(key: K): V;
113
- }
114
- //#endregion
115
- export { DefaultMap, formatBytes, getDocument, getDocumentElement, getId, getWindow, isDocument, isDocumentFragment, isElement, isElementLike, isHTMLElement, isMathMLElement, isNodeLike, isObject, isSVGElement, isShadowRoot, isTextNode, isWindowLike, once, sleep };
145
+ export { DefaultMap, formatBytes, getDocument, getDocumentElement, getId, getWindow, isDeepEqual, isDocument, isDocumentFragment, isElement, isElementLike, isHTMLElement, isMap, isMathMLElement, isNodeLike, isObject, isSVGElement, isSet, isShadowRoot, isTextNode, isWindowLike, mapGroupBy, objectGroupBy, once, sleep };
116
146
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/checker.ts","../src/dom.ts","../src/format-bytes.ts","../src/get-id.ts","../src/once.ts","../src/sleep.ts","../src/default-map.ts"],"sourcesContent":[],"mappings":";;AAGA;;iBAAgB,QAAA,2BAEJ;;;;AAFZ;;iBCGgB,SAAA,OAAgB,eAAe;;AAA/C;AAOA;AAOgB,iBAPA,UAAA,CAOoB,IAAe,EAPlB,IAOkB,CAAA,EAAA,IAAW,IAPd,IAOc;AAO9D;AAOA;AAUA;AAOgB,iBA/BA,aAAA,CA+ByB,IAAA,EA/BL,IA+BoB,CAAA,EAAA,IAAA,IA/BL,WA+BqB;AAOxE;AAOA;AAOA;AAW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A,GGpDb,CHoDa;;;;AD9DzD;;iBKAgB,KAAA,cAAmB;;;;ALAnC;;;;ACGgB,cKDH,ULCmB,CAAA,CAAe,EAAA,CAAA,CAAA,SKDT,GLCgB,CKDZ,CLCY,EKDT,CLCS,CAAA,CAAA;EAOtC,iBAAU,cAAsB;EAOhC,WAAA,CAAA,cAAa,EAAO,GAAA,GKZA,CLYe,EAAA,QAAW,CAAA,EKZZ,QLYY,CAAA,SAAA,CKZO,CLYP,EKZU,CLYV,CAAA,CAAA;EAO9C,GAAA,CAAA,GAAA,EKdI,CLcJ,CAAA,EKdQ,CLcR;AAOhB"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/checker.ts","../src/default-map.ts","../src/dom.ts","../src/format-bytes.ts","../src/get-id.ts","../src/is-deep-equal.ts","../src/map-group-by.ts","../src/object-group-by.ts","../src/once.ts","../src/sleep.ts"],"sourcesContent":[],"mappings":";;AAGA;AASA;AAOgB,iBAhBA,QAAA,CAgBmC,KAAA,EAAA,OAAA,CAAA,EAAA,KAAA,IAdvC,MAcuC,CAAA,MAAA,GAAA,MAAA,GAAA,MAAA,EAAA,OAAA,CAAA;;;;ACdtC,iBDOG,KAAA,CCPO,KAAA,EAAA,OAAA,CAAA,EAAA,KAAA,IDOyB,GCPzB,CAAA,OAAA,EAAA,OAAA,CAAA;;;;AAG8C,iBDWrD,KAAA,CCXqD,KAAA,EAAA,OAAA,CAAA,EAAA,KAAA,IDWrB,GCXqB,CAAA,OAAA,CAAA;;;;ADLrE;AASA;AAOA;;cCda,yBAAyB,IAAI,GAAG;;EAAhC,WAAA,CAAA,cAAU,EAAA,GAAA,GAGa,CAHb,EAAA,QAAA,CAAA,EAG2B,QAH3B,CAAA,SAAA,CAG8C,CAH9C,EAGiD,CAHjD,CAAA,CAAA;EAAmB,GAAA,CAAA,GAAA,EAQtB,CARsB,CAAA,EAQlB,CARkB;;;;;ADF1C;AASA;AAOgB,iBEbA,SAAA,CFamC,IAAA,EEbnB,IFamB,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AA;;;;AAhBnD;AASA;AAOgB,iBKdA,WAAA,CLcmC,CAAA,EAAA,OAAA,EAAA,CAAA,EAAA,OAAA,CAAA,EAAA,OAAA;;;;;;;;ACXD,cK6BrC,UL7BqC,EAAA,CAAA,CAAA,EAAA,CAAA,CAAA,CAAA,KAAA,EK8BzC,QL9ByC,CK8BhC,CL9BgC,CAAA,EAAA,WAAA,EAAA,CAAA,IAAA,EK+B5B,CL/B4B,EAAA,KAAA,EAAA,MAAA,EAAA,GK+BP,CL/BO,EAAA,GKgC7C,GLhC6C,CKgCzC,CLhCyC,EKgCtC,CLhCsC,EAAA,CAAA;;;;;;;;AAAA,cM6BrC,aN7BqC,EAAA,CAAA,UM6BX,WN7BW,EAAA,CAAA,CAAA,CAAA,KAAA,EM8BzC,QN9ByC,CM8BhC,CN9BgC,CAAA,EAAA,WAAA,EAAA,CAAA,IAAA,EM+B5B,CN/B4B,EAAA,KAAA,EAAA,MAAA,EAAA,GM+BP,CN/BO,EAAA,GMgC7C,ONhC6C,CMgCrC,MNhCqC,CMgC9B,CNhC8B,EMgC3B,CNhC2B,EAAA,CAAA,CAAA;;;;ADLlD;AASA;AAOA;;;;ACdA;;;;;;AAGkD,iBOKlC,IPLkC,CAAA,CAAA,CAAA,CAAA,EAAA,EAAA,GAAA,GOKhB,CPLgB,CAAA,EAAA,GAAA,GOKN,CPLM;;;;ADLlD;AASA;AAOgB,iBShBA,KAAA,CTgBmC,EAAA,EAAA,MAAA,CAAA,EShBhB,OTgBgB,CAAA,IAAA,CAAA"}
package/dist/index.js CHANGED
@@ -5,6 +5,38 @@
5
5
  function isObject(value) {
6
6
  return value != null && typeof value === "object";
7
7
  }
8
+ /**
9
+ * Checks if the given value is a Map.
10
+ */
11
+ function isMap(value) {
12
+ return value instanceof Map;
13
+ }
14
+ /**
15
+ * Checks if the given value is a Set.
16
+ */
17
+ function isSet(value) {
18
+ return value instanceof Set;
19
+ }
20
+
21
+ //#endregion
22
+ //#region src/default-map.ts
23
+ /**
24
+ * A map that automatically creates values for missing keys using a factory function.
25
+ *
26
+ * Similar to Python's [defaultdict](https://docs.python.org/3.13/library/collections.html#collections.defaultdict).
27
+ */
28
+ var DefaultMap = class extends Map {
29
+ constructor(defaultFactory, iterable) {
30
+ super(iterable);
31
+ this.defaultFactory = defaultFactory;
32
+ }
33
+ get(key) {
34
+ if (this.has(key)) return super.get(key);
35
+ const value = this.defaultFactory();
36
+ this.set(key, value);
37
+ return value;
38
+ }
39
+ };
8
40
 
9
41
  //#endregion
10
42
  //#region src/dom-node-type.ts
@@ -147,6 +179,109 @@ function getId() {
147
179
  return id;
148
180
  }
149
181
 
182
+ //#endregion
183
+ //#region src/is-deep-equal.ts
184
+ /**
185
+ * Whether two values are deeply equal.
186
+ */
187
+ function isDeepEqual(a, b) {
188
+ if (a === b) return true;
189
+ if (a == null || b == null) return false;
190
+ const aType = typeof a;
191
+ if (aType !== typeof b) return false;
192
+ if (aType === "number" && Number.isNaN(a) && Number.isNaN(b)) return true;
193
+ if (Array.isArray(a)) {
194
+ if (!Array.isArray(b)) return false;
195
+ if (a.length !== b.length) return false;
196
+ const size = a.length;
197
+ for (let i = 0; i < size; i++) if (!isDeepEqual(a[i], b[i])) return false;
198
+ return true;
199
+ }
200
+ if (isSet(a)) {
201
+ if (!isSet(b)) return false;
202
+ if (a.size !== b.size) return false;
203
+ for (const value of a) if (!b.has(value)) return false;
204
+ return true;
205
+ }
206
+ if (isMap(a)) {
207
+ if (!isMap(b)) return false;
208
+ if (a.size !== b.size) return false;
209
+ for (const key of a.keys()) {
210
+ if (!b.has(key)) return false;
211
+ if (!isDeepEqual(a.get(key), b.get(key))) return false;
212
+ }
213
+ return true;
214
+ }
215
+ if (typeof a === "object" && typeof b === "object") {
216
+ const aKeys = Object.keys(a);
217
+ const bKeys = Object.keys(b);
218
+ if (aKeys.length !== bKeys.length) return false;
219
+ for (const key of aKeys) if (!isDeepEqual(a[key], b[key])) return false;
220
+ return true;
221
+ }
222
+ return false;
223
+ }
224
+
225
+ //#endregion
226
+ //#region src/map-group-by.ts
227
+ /**
228
+ * @internal
229
+ */
230
+ function mapGroupByPolyfill(items, keySelector) {
231
+ const map = /* @__PURE__ */ new Map();
232
+ let index = 0;
233
+ for (const item of items) {
234
+ const key = keySelector(item, index);
235
+ const group = map.get(key);
236
+ if (group) group.push(item);
237
+ else map.set(key, [item]);
238
+ index++;
239
+ }
240
+ return map;
241
+ }
242
+ /**
243
+ * @internal
244
+ */
245
+ function mapGroupByNative(items, keySelector) {
246
+ return Map.groupBy(items, keySelector);
247
+ }
248
+ /**
249
+ * A polyfill for the `Map.groupBy` static method.
250
+ *
251
+ * @public
252
+ */
253
+ const mapGroupBy = !!Map.groupBy ? mapGroupByNative : mapGroupByPolyfill;
254
+
255
+ //#endregion
256
+ //#region src/object-group-by.ts
257
+ /**
258
+ * @internal
259
+ */
260
+ function objectGroupByPolyfill(items, keySelector) {
261
+ const result = {};
262
+ let index = 0;
263
+ for (const item of items) {
264
+ const key = keySelector(item, index);
265
+ const group = result[key];
266
+ if (group) group.push(item);
267
+ else result[key] = [item];
268
+ index++;
269
+ }
270
+ return result;
271
+ }
272
+ /**
273
+ * @internal
274
+ */
275
+ function objectGroupByNative(items, keySelector) {
276
+ return Object.groupBy(items, keySelector);
277
+ }
278
+ /**
279
+ * A polyfill for the `Object.groupBy` static method.
280
+ *
281
+ * @public
282
+ */
283
+ const objectGroupBy = !!Object.groupBy ? objectGroupByNative : objectGroupByPolyfill;
284
+
150
285
  //#endregion
151
286
  //#region src/once.ts
152
287
  /**
@@ -185,25 +320,5 @@ function sleep(ms) {
185
320
  }
186
321
 
187
322
  //#endregion
188
- //#region src/default-map.ts
189
- /**
190
- * A map that automatically creates values for missing keys using a factory function.
191
- *
192
- * Similar to Python's [defaultdict](https://docs.python.org/3.13/library/collections.html#collections.defaultdict).
193
- */
194
- var DefaultMap = class extends Map {
195
- constructor(defaultFactory, iterable) {
196
- super(iterable);
197
- this.defaultFactory = defaultFactory;
198
- }
199
- get(key) {
200
- if (this.has(key)) return super.get(key);
201
- const value = this.defaultFactory();
202
- this.set(key, value);
203
- return value;
204
- }
205
- };
206
-
207
- //#endregion
208
- export { DefaultMap, formatBytes, getDocument, getDocumentElement, getId, getWindow, isDocument, isDocumentFragment, isElement, isElementLike, isHTMLElement, isMathMLElement, isNodeLike, isObject, isSVGElement, isShadowRoot, isTextNode, isWindowLike, once, sleep };
323
+ export { DefaultMap, formatBytes, getDocument, getDocumentElement, getId, getWindow, isDeepEqual, isDocument, isDocumentFragment, isElement, isElementLike, isHTMLElement, isMap, isMathMLElement, isNodeLike, isObject, isSVGElement, isSet, isShadowRoot, isTextNode, isWindowLike, mapGroupBy, objectGroupBy, once, sleep };
209
324
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["NodeType.ELEMENT_NODE","NodeType.TEXT_NODE","NodeType.DOCUMENT_NODE","NodeType.DOCUMENT_FRAGMENT_NODE","result: T"],"sources":["../src/checker.ts","../src/dom-node-type.ts","../src/dom.ts","../src/format-bytes.ts","../src/get-id.ts","../src/once.ts","../src/sleep.ts","../src/default-map.ts"],"sourcesContent":["/**\n * Checks if the given value is an object.\n */\nexport function isObject(\n value: unknown,\n): value is Record<string | symbol | number, unknown> {\n return value != null && typeof value === 'object'\n}\n","// prettier-ignore\nexport const ELEMENT_NODE = 1 satisfies typeof Node.ELEMENT_NODE;\n// prettier-ignore\nexport const ATTRIBUTE_NODE = 2 satisfies typeof Node.ATTRIBUTE_NODE;\n// prettier-ignore\nexport const TEXT_NODE = 3 satisfies typeof Node.TEXT_NODE;\n// prettier-ignore\nexport const CDATA_SECTION_NODE = 4 satisfies typeof Node.CDATA_SECTION_NODE;\n// prettier-ignore\nexport const ENTITY_REFERENCE_NODE = 5 satisfies typeof Node.ENTITY_REFERENCE_NODE;\n// prettier-ignore\nexport const ENTITY_NODE = 6 satisfies typeof Node.ENTITY_NODE;\n// prettier-ignore\nexport const PROCESSING_INSTRUCTION_NODE = 7 satisfies typeof Node.PROCESSING_INSTRUCTION_NODE;\n// prettier-ignore\nexport const COMMENT_NODE = 8 satisfies typeof Node.COMMENT_NODE;\n// prettier-ignore\nexport const DOCUMENT_NODE = 9 satisfies typeof Node.DOCUMENT_NODE;\n// prettier-ignore\nexport const DOCUMENT_TYPE_NODE = 10 satisfies typeof Node.DOCUMENT_TYPE_NODE;\n// prettier-ignore\nexport const DOCUMENT_FRAGMENT_NODE = 11 satisfies typeof Node.DOCUMENT_FRAGMENT_NODE;\n// prettier-ignore\nexport const NOTATION_NODE = 12 satisfies typeof Node.NOTATION_NODE;\n","import { isObject } from './checker'\nimport * as NodeType from './dom-node-type'\n\n/**\n * Checks if the given DOM node is an Element.\n */\nexport function isElement(node: Node): node is Element {\n return node.nodeType === NodeType.ELEMENT_NODE\n}\n\n/**\n * Checks if the given DOM node is a Text node.\n */\nexport function isTextNode(node: Node): node is Text {\n return node.nodeType === NodeType.TEXT_NODE\n}\n\n/**\n * Checks if the given DOM node is an HTMLElement.\n */\nexport function isHTMLElement(node: Node): node is HTMLElement {\n return isElement(node) && node.namespaceURI === 'http://www.w3.org/1999/xhtml'\n}\n\n/**\n * Checks if the given DOM node is an SVGElement.\n */\nexport function isSVGElement(node: Node): node is SVGElement {\n return isElement(node) && node.namespaceURI === 'http://www.w3.org/2000/svg'\n}\n\n/**\n * Checks if the given DOM node is an MathMLElement.\n */\nexport function isMathMLElement(node: Node): node is MathMLElement {\n return (\n isElement(node) &&\n node.namespaceURI === 'http://www.w3.org/1998/Math/MathML'\n )\n}\n\n/**\n * Checks if the given DOM node is a Document.\n */\nexport function isDocument(node: Node): node is Document {\n return node.nodeType === NodeType.DOCUMENT_NODE\n}\n\n/**\n * Checks if the given DOM node is a DocumentFragment.\n */\nexport function isDocumentFragment(node: Node): node is DocumentFragment {\n return node.nodeType === NodeType.DOCUMENT_FRAGMENT_NODE\n}\n\n/**\n * Checks if the given DOM node is a ShadowRoot.\n */\nexport function isShadowRoot(node: Node): node is ShadowRoot {\n return isDocumentFragment(node) && 'host' in node && isElementLike(node.host)\n}\n\n/**\n * Checks if an unknown value is likely a DOM node.\n */\nexport function isNodeLike(value: unknown): value is Node {\n return isObject(value) && value.nodeType !== undefined\n}\n\n/**\n * Checks if an unknown value is likely a DOM element.\n */\nexport function isElementLike(value: unknown): value is Element {\n return (\n isObject(value) &&\n value.nodeType === NodeType.ELEMENT_NODE &&\n typeof value.nodeName === 'string'\n )\n}\n\n/**\n * Checks if the given value is likely a Window object.\n */\nexport function isWindowLike(value: unknown): value is Window {\n return isObject(value) && value.window === value\n}\n\n/**\n * Gets the window object for the given target or the global window object if no\n * target is provided.\n */\nexport function getWindow(\n target?: Node | ShadowRoot | Document | null,\n): Window & typeof globalThis {\n if (target) {\n if (isShadowRoot(target)) {\n return getWindow(target.host)\n }\n if (isDocument(target)) {\n return target.defaultView || window\n }\n if (isElement(target)) {\n return target.ownerDocument?.defaultView || window\n }\n }\n return window\n}\n\n/**\n * Gets the document for the given target or the global document if no target is\n * provided.\n */\nexport function getDocument(\n target?: Element | Window | Node | Document | null,\n): Document {\n if (target) {\n if (isWindowLike(target)) {\n return target.document\n }\n if (isDocument(target)) {\n return target\n }\n return target.ownerDocument || document\n }\n return document\n}\n\n/**\n * Gets a reference to the root node of the document based on the given target.\n */\nexport function getDocumentElement(\n target?: Element | Node | Window | Document | null,\n): HTMLElement {\n return getDocument(target).documentElement\n}\n","/**\n * Formats a number of bytes into a human-readable string.\n * @param bytes - The number of bytes to format.\n * @returns A string representing the number of bytes in a human-readable format.\n */\nexport function formatBytes(bytes: number): string {\n const units = ['B', 'KB', 'MB', 'GB']\n let unitIndex = 0\n let num = bytes\n while (Math.abs(num) >= 1024 && unitIndex < units.length - 1) {\n num /= 1024\n unitIndex++\n }\n const fraction = unitIndex === 0 && num % 1 === 0 ? 0 : 1\n return `${num.toFixed(fraction)}${units[unitIndex]}`\n}\n","let id = 0\n\n/**\n * Generates a unique positive integer.\n */\nexport function getId(): number {\n id = (id % Number.MAX_SAFE_INTEGER) + 1\n return id\n}\n","/**\n * Creates a function that will only execute the provided function once.\n * Subsequent calls will return the cached result from the first execution.\n *\n * @param fn The function to execute once\n * @returns A function that will only execute the provided function once\n * @example\n * ```ts\n * const getValue = once(() => expensiveOperation())\n * getValue() // executes expensiveOperation\n * getValue() // returns cached result\n * ```\n */\nexport function once<T>(fn: () => T): () => T {\n let called = false\n let result: T\n return () => {\n if (!called) {\n result = fn()\n called = true\n // @ts-expect-error - micro-optimization for memory management\n fn = undefined\n }\n return result\n }\n}\n","/**\n * Sleep for a given number of milliseconds.\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n","/**\n * A map that automatically creates values for missing keys using a factory function.\n *\n * Similar to Python's [defaultdict](https://docs.python.org/3.13/library/collections.html#collections.defaultdict).\n */\nexport class DefaultMap<K, V> extends Map<K, V> {\n private readonly defaultFactory: () => V\n\n constructor(defaultFactory: () => V, iterable?: Iterable<readonly [K, V]>) {\n super(iterable)\n this.defaultFactory = defaultFactory\n }\n\n override get(key: K): V {\n if (this.has(key)) {\n return super.get(key)!\n }\n const value = this.defaultFactory()\n this.set(key, value)\n return value\n }\n}\n"],"mappings":";;;;AAGA,SAAgB,SACd,OACoD;AACpD,QAAO,SAAS,QAAQ,OAAO,UAAU;;;;;ACL3C,MAAa,eAAe;AAI5B,MAAa,YAAY;AAYzB,MAAa,gBAAgB;AAI7B,MAAa,yBAAyB;;;;;;;ACftC,SAAgB,UAAU,MAA6B;AACrD,QAAO,KAAK,aAAaA;;;;;AAM3B,SAAgB,WAAW,MAA0B;AACnD,QAAO,KAAK,aAAaC;;;;;AAM3B,SAAgB,cAAc,MAAiC;AAC7D,QAAO,UAAU,KAAK,IAAI,KAAK,iBAAiB;;;;;AAMlD,SAAgB,aAAa,MAAgC;AAC3D,QAAO,UAAU,KAAK,IAAI,KAAK,iBAAiB;;;;;AAMlD,SAAgB,gBAAgB,MAAmC;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AAG,IAAI,QAAQ,SAAS,GAAG,MAAM;;;;;ACd1C,IAAI,KAAK;;;;AAKT,SAAgB,QAAgB;AAC9B,MAAM,KAAK,OAAO,mBAAoB;AACtC,QAAO;;;;;;;;;;;;;;;;;;ACMT,SAAgB,KAAQ,IAAsB;CAC5C,IAAI,SAAS;CACb,IAAII;AACJ,cAAa;AACX,MAAI,CAAC,QAAQ;AACX,YAAS,IAAI;AACb,YAAS;AAET,QAAK;;AAEP,SAAO;;;;;;;;;ACpBX,SAAgB,MAAM,IAA2B;AAC/C,QAAO,IAAI,SAAS,YAAY,WAAW,SAAS,GAAG,CAAC;;;;;;;;;;ACC1D,IAAa,aAAb,cAAsC,IAAU;CAG9C,YAAY,gBAAyB,UAAsC;AACzE,QAAM,SAAS;AACf,OAAK,iBAAiB;;CAGxB,AAAS,IAAI,KAAW;AACtB,MAAI,KAAK,IAAI,IAAI,CACf,QAAO,MAAM,IAAI,IAAI;EAEvB,MAAM,QAAQ,KAAK,gBAAgB;AACnC,OAAK,IAAI,KAAK,MAAM;AACpB,SAAO"}
1
+ {"version":3,"file":"index.js","names":["NodeType.ELEMENT_NODE","NodeType.TEXT_NODE","NodeType.DOCUMENT_NODE","NodeType.DOCUMENT_FRAGMENT_NODE","mapGroupBy: <K, T>(\n items: Iterable<T>,\n keySelector: (item: T, index: number) => K,\n) => Map<K, T[]>","result: Partial<Record<K, T[]>>","objectGroupBy: <K extends PropertyKey, T>(\n items: Iterable<T>,\n keySelector: (item: T, index: number) => K,\n) => Partial<Record<K, T[]>>","result: T"],"sources":["../src/checker.ts","../src/default-map.ts","../src/dom-node-type.ts","../src/dom.ts","../src/format-bytes.ts","../src/get-id.ts","../src/is-deep-equal.ts","../src/map-group-by.ts","../src/object-group-by.ts","../src/once.ts","../src/sleep.ts"],"sourcesContent":["/**\n * Checks if the given value is an object.\n */\nexport function isObject(\n value: unknown,\n): value is Record<string | symbol | number, unknown> {\n return value != null && typeof value === 'object'\n}\n\n/**\n * Checks if the given value is a Map.\n */\nexport function isMap(value: unknown): value is Map<unknown, unknown> {\n return value instanceof Map\n}\n\n/**\n * Checks if the given value is a Set.\n */\nexport function isSet(value: unknown): value is Set<unknown> {\n return value instanceof Set\n}\n","/**\n * A map that automatically creates values for missing keys using a factory function.\n *\n * Similar to Python's [defaultdict](https://docs.python.org/3.13/library/collections.html#collections.defaultdict).\n */\nexport class DefaultMap<K, V> extends Map<K, V> {\n private readonly defaultFactory: () => V\n\n constructor(defaultFactory: () => V, iterable?: Iterable<readonly [K, V]>) {\n super(iterable)\n this.defaultFactory = defaultFactory\n }\n\n override get(key: K): V {\n if (this.has(key)) {\n return super.get(key)!\n }\n const value = this.defaultFactory()\n this.set(key, value)\n return value\n }\n}\n","// prettier-ignore\nexport const ELEMENT_NODE = 1 satisfies typeof Node.ELEMENT_NODE;\n// prettier-ignore\nexport const ATTRIBUTE_NODE = 2 satisfies typeof Node.ATTRIBUTE_NODE;\n// prettier-ignore\nexport const TEXT_NODE = 3 satisfies typeof Node.TEXT_NODE;\n// prettier-ignore\nexport const CDATA_SECTION_NODE = 4 satisfies typeof Node.CDATA_SECTION_NODE;\n// prettier-ignore\nexport const ENTITY_REFERENCE_NODE = 5 satisfies typeof Node.ENTITY_REFERENCE_NODE;\n// prettier-ignore\nexport const ENTITY_NODE = 6 satisfies typeof Node.ENTITY_NODE;\n// prettier-ignore\nexport const PROCESSING_INSTRUCTION_NODE = 7 satisfies typeof Node.PROCESSING_INSTRUCTION_NODE;\n// prettier-ignore\nexport const COMMENT_NODE = 8 satisfies typeof Node.COMMENT_NODE;\n// prettier-ignore\nexport const DOCUMENT_NODE = 9 satisfies typeof Node.DOCUMENT_NODE;\n// prettier-ignore\nexport const DOCUMENT_TYPE_NODE = 10 satisfies typeof Node.DOCUMENT_TYPE_NODE;\n// prettier-ignore\nexport const DOCUMENT_FRAGMENT_NODE = 11 satisfies typeof Node.DOCUMENT_FRAGMENT_NODE;\n// prettier-ignore\nexport const NOTATION_NODE = 12 satisfies typeof Node.NOTATION_NODE;\n","import { isObject } from './checker'\nimport * as NodeType from './dom-node-type'\n\n/**\n * Checks if the given DOM node is an Element.\n */\nexport function isElement(node: Node): node is Element {\n return node.nodeType === NodeType.ELEMENT_NODE\n}\n\n/**\n * Checks if the given DOM node is a Text node.\n */\nexport function isTextNode(node: Node): node is Text {\n return node.nodeType === NodeType.TEXT_NODE\n}\n\n/**\n * Checks if the given DOM node is an HTMLElement.\n */\nexport function isHTMLElement(node: Node): node is HTMLElement {\n return isElement(node) && node.namespaceURI === 'http://www.w3.org/1999/xhtml'\n}\n\n/**\n * Checks if the given DOM node is an SVGElement.\n */\nexport function isSVGElement(node: Node): node is SVGElement {\n return isElement(node) && node.namespaceURI === 'http://www.w3.org/2000/svg'\n}\n\n/**\n * Checks if the given DOM node is an MathMLElement.\n */\nexport function isMathMLElement(node: Node): node is MathMLElement {\n return (\n isElement(node) &&\n node.namespaceURI === 'http://www.w3.org/1998/Math/MathML'\n )\n}\n\n/**\n * Checks if the given DOM node is a Document.\n */\nexport function isDocument(node: Node): node is Document {\n return node.nodeType === NodeType.DOCUMENT_NODE\n}\n\n/**\n * Checks if the given DOM node is a DocumentFragment.\n */\nexport function isDocumentFragment(node: Node): node is DocumentFragment {\n return node.nodeType === NodeType.DOCUMENT_FRAGMENT_NODE\n}\n\n/**\n * Checks if the given DOM node is a ShadowRoot.\n */\nexport function isShadowRoot(node: Node): node is ShadowRoot {\n return isDocumentFragment(node) && 'host' in node && isElementLike(node.host)\n}\n\n/**\n * Checks if an unknown value is likely a DOM node.\n */\nexport function isNodeLike(value: unknown): value is Node {\n return isObject(value) && value.nodeType !== undefined\n}\n\n/**\n * Checks if an unknown value is likely a DOM element.\n */\nexport function isElementLike(value: unknown): value is Element {\n return (\n isObject(value) &&\n value.nodeType === NodeType.ELEMENT_NODE &&\n typeof value.nodeName === 'string'\n )\n}\n\n/**\n * Checks if the given value is likely a Window object.\n */\nexport function isWindowLike(value: unknown): value is Window {\n return isObject(value) && value.window === value\n}\n\n/**\n * Gets the window object for the given target or the global window object if no\n * target is provided.\n */\nexport function getWindow(\n target?: Node | ShadowRoot | Document | null,\n): Window & typeof globalThis {\n if (target) {\n if (isShadowRoot(target)) {\n return getWindow(target.host)\n }\n if (isDocument(target)) {\n return target.defaultView || window\n }\n if (isElement(target)) {\n return target.ownerDocument?.defaultView || window\n }\n }\n return window\n}\n\n/**\n * Gets the document for the given target or the global document if no target is\n * provided.\n */\nexport function getDocument(\n target?: Element | Window | Node | Document | null,\n): Document {\n if (target) {\n if (isWindowLike(target)) {\n return target.document\n }\n if (isDocument(target)) {\n return target\n }\n return target.ownerDocument || document\n }\n return document\n}\n\n/**\n * Gets a reference to the root node of the document based on the given target.\n */\nexport function getDocumentElement(\n target?: Element | Node | Window | Document | null,\n): HTMLElement {\n return getDocument(target).documentElement\n}\n","/**\n * Formats a number of bytes into a human-readable string.\n * @param bytes - The number of bytes to format.\n * @returns A string representing the number of bytes in a human-readable format.\n */\nexport function formatBytes(bytes: number): string {\n const units = ['B', 'KB', 'MB', 'GB']\n let unitIndex = 0\n let num = bytes\n while (Math.abs(num) >= 1024 && unitIndex < units.length - 1) {\n num /= 1024\n unitIndex++\n }\n const fraction = unitIndex === 0 && num % 1 === 0 ? 0 : 1\n return `${num.toFixed(fraction)}${units[unitIndex]}`\n}\n","let id = 0\n\n/**\n * Generates a unique positive integer.\n */\nexport function getId(): number {\n id = (id % Number.MAX_SAFE_INTEGER) + 1\n return id\n}\n","import { isMap, isSet } from './checker'\n\n/**\n * Whether two values are deeply equal.\n */\nexport function isDeepEqual(a: unknown, b: unknown): boolean {\n if (a === b) {\n return true\n }\n\n // Handle null and undefined early\n if (a == null || b == null) {\n return false\n }\n\n const aType = typeof a\n const bType = typeof b\n if (aType !== bType) {\n return false\n }\n\n if (aType === 'number' && Number.isNaN(a) && Number.isNaN(b)) {\n return true\n }\n\n if (Array.isArray(a)) {\n if (!Array.isArray(b)) {\n return false\n }\n if (a.length !== b.length) {\n return false\n }\n const size = a.length\n for (let i = 0; i < size; i++) {\n if (!isDeepEqual(a[i], b[i])) {\n return false\n }\n }\n return true\n }\n\n if (isSet(a)) {\n if (!isSet(b)) {\n return false\n }\n if (a.size !== b.size) {\n return false\n }\n for (const value of a) {\n if (!b.has(value)) {\n return false\n }\n }\n return true\n }\n\n if (isMap(a)) {\n if (!isMap(b)) {\n return false\n }\n if (a.size !== b.size) {\n return false\n }\n for (const key of a.keys()) {\n if (!b.has(key)) {\n return false\n }\n if (!isDeepEqual(a.get(key), b.get(key))) {\n return false\n }\n }\n return true\n }\n\n if (typeof a === 'object' && typeof b === 'object') {\n const aKeys = Object.keys(a)\n const bKeys = Object.keys(b)\n if (aKeys.length !== bKeys.length) {\n return false\n }\n for (const key of aKeys) {\n if (\n !isDeepEqual(\n (a as Record<string, unknown>)[key],\n (b as Record<string, unknown>)[key],\n )\n ) {\n return false\n }\n }\n return true\n }\n\n return false\n}\n","/**\n * @internal\n */\nexport function mapGroupByPolyfill<K, T>(\n items: Iterable<T>,\n keySelector: (item: T, index: number) => K,\n): Map<K, T[]> {\n const map = new Map<K, T[]>()\n let index = 0\n for (const item of items) {\n const key = keySelector(item, index)\n const group = map.get(key)\n if (group) {\n group.push(item)\n } else {\n map.set(key, [item])\n }\n index++\n }\n return map\n}\n\n/**\n * @internal\n */\nexport function mapGroupByNative<K, T>(\n items: Iterable<T>,\n keySelector: (item: T, index: number) => K,\n): Map<K, T[]> {\n return Map.groupBy(items, keySelector)\n}\n\n/**\n * A polyfill for the `Map.groupBy` static method.\n *\n * @public\n */\nexport const mapGroupBy: <K, T>(\n items: Iterable<T>,\n keySelector: (item: T, index: number) => K,\n) => Map<K, T[]> = !!Map.groupBy ? mapGroupByNative : mapGroupByPolyfill\n","/**\n * @internal\n */\nexport function objectGroupByPolyfill<K extends PropertyKey, T>(\n items: Iterable<T>,\n keySelector: (item: T, index: number) => K,\n): Partial<Record<K, T[]>> {\n const result: Partial<Record<K, T[]>> = {}\n let index = 0\n for (const item of items) {\n const key = keySelector(item, index)\n const group = result[key]\n if (group) {\n group.push(item)\n } else {\n result[key] = [item]\n }\n index++\n }\n return result\n}\n\n/**\n * @internal\n */\nexport function objectGroupByNative<K extends PropertyKey, T>(\n items: Iterable<T>,\n keySelector: (item: T, index: number) => K,\n): Partial<Record<K, T[]>> {\n return Object.groupBy(items, keySelector)\n}\n\n/**\n * A polyfill for the `Object.groupBy` static method.\n *\n * @public\n */\nexport const objectGroupBy: <K extends PropertyKey, T>(\n items: Iterable<T>,\n keySelector: (item: T, index: number) => K,\n) => Partial<Record<K, T[]>> = !!Object.groupBy\n ? objectGroupByNative\n : objectGroupByPolyfill\n","/**\n * Creates a function that will only execute the provided function once.\n * Subsequent calls will return the cached result from the first execution.\n *\n * @param fn The function to execute once\n * @returns A function that will only execute the provided function once\n * @example\n * ```ts\n * const getValue = once(() => expensiveOperation())\n * getValue() // executes expensiveOperation\n * getValue() // returns cached result\n * ```\n */\nexport function once<T>(fn: () => T): () => T {\n let called = false\n let result: T\n return () => {\n if (!called) {\n result = fn()\n called = true\n // @ts-expect-error - micro-optimization for memory management\n fn = undefined\n }\n return result\n }\n}\n","/**\n * Sleep for a given number of milliseconds.\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n"],"mappings":";;;;AAGA,SAAgB,SACd,OACoD;AACpD,QAAO,SAAS,QAAQ,OAAO,UAAU;;;;;AAM3C,SAAgB,MAAM,OAAgD;AACpE,QAAO,iBAAiB;;;;;AAM1B,SAAgB,MAAM,OAAuC;AAC3D,QAAO,iBAAiB;;;;;;;;;;ACf1B,IAAa,aAAb,cAAsC,IAAU;CAG9C,YAAY,gBAAyB,UAAsC;AACzE,QAAM,SAAS;AACf,OAAK,iBAAiB;;CAGxB,AAAS,IAAI,KAAW;AACtB,MAAI,KAAK,IAAI,IAAI,CACf,QAAO,MAAM,IAAI,IAAI;EAEvB,MAAM,QAAQ,KAAK,gBAAgB;AACnC,OAAK,IAAI,KAA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KAAK;MAEhB,QAAO,OAAO,CAAC,KAAK;AAEtB;;AAEF,QAAO;;;;;AAMT,SAAgB,oBACd,OACA,aACyB;AACzB,QAAO,OAAO,QAAQ,OAAO,YAAY;;;;;;;AAQ3C,MAAaC,gBAGkB,CAAC,CAAC,OAAO,UACpC,sBACA;;;;;;;;;;;;;;;;;AC7BJ,SAAgB,KAAQ,IAAsB;CAC5C,IAAI,SAAS;CACb,IAAIC;AACJ,cAAa;AACX,MAAI,CAAC,QAAQ;AACX,YAAS,IAAI;AACb,YAAS;AAET,QAAK;;AAEP,SAAO;;;;;;;;;ACpBX,SAAgB,MAAM,IAA2B;AAC/C,QAAO,IAAI,SAAS,YAAY,WAAW,SAAS,GAAG,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ocavue/utils",
3
3
  "type": "module",
4
- "version": "0.9.0",
4
+ "version": "1.1.0",
5
5
  "description": "A collection of utility functions for the browser and other environments",
6
6
  "author": "ocavue <ocavue@gmail.com>",
7
7
  "license": "MIT",
@@ -55,16 +55,16 @@
55
55
  "publishConfig": {
56
56
  "access": "public"
57
57
  },
58
- "size-limit": [
59
- {
60
- "path": "dist/index.js"
61
- }
62
- ],
63
58
  "renovate": {
64
59
  "extends": [
65
60
  "github>ocavue/config-renovate"
66
61
  ]
67
62
  },
63
+ "size-limit": [
64
+ {
65
+ "path": "dist/index.js"
66
+ }
67
+ ],
68
68
  "scripts": {
69
69
  "build": "tsdown",
70
70
  "dev": "tsdown --watch",
@@ -2,7 +2,7 @@
2
2
 
3
3
  import { describe, expect, it } from 'vitest'
4
4
 
5
- import { isObject } from './checker'
5
+ import { isMap, isObject, isSet } from './checker'
6
6
 
7
7
  describe('isObject', () => {
8
8
  it('returns true for plain objects', () => {
@@ -38,3 +38,37 @@ describe('isObject', () => {
38
38
  expect(isObject(new TestClass())).toBe(true)
39
39
  })
40
40
  })
41
+
42
+ describe('isMap', () => {
43
+ it('returns true for Map instances', () => {
44
+ expect(isMap(new Map())).toBe(true)
45
+ expect(isMap(new Map([['key', 'value']]))).toBe(true)
46
+ })
47
+
48
+ it('returns false for non-Map values', () => {
49
+ expect(isMap({})).toBe(false)
50
+ expect(isMap([])).toBe(false)
51
+ expect(isMap(new Set())).toBe(false)
52
+ expect(isMap(null)).toBe(false)
53
+ expect(isMap(undefined)).toBe(false)
54
+ expect(isMap('map')).toBe(false)
55
+ expect(isMap(42)).toBe(false)
56
+ })
57
+ })
58
+
59
+ describe('isSet', () => {
60
+ it('returns true for Set instances', () => {
61
+ expect(isSet(new Set())).toBe(true)
62
+ expect(isSet(new Set([1, 2, 3]))).toBe(true)
63
+ })
64
+
65
+ it('returns false for non-Set values', () => {
66
+ expect(isSet({})).toBe(false)
67
+ expect(isSet([])).toBe(false)
68
+ expect(isSet(new Map())).toBe(false)
69
+ expect(isSet(null)).toBe(false)
70
+ expect(isSet(undefined)).toBe(false)
71
+ expect(isSet('set')).toBe(false)
72
+ expect(isSet(42)).toBe(false)
73
+ })
74
+ })
package/src/checker.ts CHANGED
@@ -6,3 +6,17 @@ export function isObject(
6
6
  ): value is Record<string | symbol | number, unknown> {
7
7
  return value != null && typeof value === 'object'
8
8
  }
9
+
10
+ /**
11
+ * Checks if the given value is a Map.
12
+ */
13
+ export function isMap(value: unknown): value is Map<unknown, unknown> {
14
+ return value instanceof Map
15
+ }
16
+
17
+ /**
18
+ * Checks if the given value is a Set.
19
+ */
20
+ export function isSet(value: unknown): value is Set<unknown> {
21
+ return value instanceof Set
22
+ }
@@ -144,10 +144,13 @@ describe('DefaultMap', () => {
144
144
  })
145
145
 
146
146
  it('works with iteration methods', () => {
147
- const map = new DefaultMap<string, number>(() => 0, [
148
- ['a', 1],
149
- ['b', 2],
150
- ])
147
+ const map = new DefaultMap<string, number>(
148
+ () => 0,
149
+ [
150
+ ['a', 1],
151
+ ['b', 2],
152
+ ],
153
+ )
151
154
 
152
155
  expect([...map.keys()]).toEqual(['a', 'b'])
153
156
  expect([...map.values()]).toEqual([1, 2])
package/src/index.ts CHANGED
@@ -1,7 +1,10 @@
1
1
  export * from './checker'
2
+ export { DefaultMap } from './default-map'
2
3
  export * from './dom'
3
4
  export { formatBytes } from './format-bytes'
4
5
  export { getId } from './get-id'
6
+ export { isDeepEqual } from './is-deep-equal'
7
+ export { mapGroupBy } from './map-group-by'
8
+ export { objectGroupBy } from './object-group-by'
5
9
  export { once } from './once'
6
10
  export { sleep } from './sleep'
7
- export { DefaultMap } from './default-map'
@@ -0,0 +1,223 @@
1
+ // @vitest-environment node
2
+
3
+ import { describe, expect, it } from 'vitest'
4
+
5
+ import { isDeepEqual } from './is-deep-equal'
6
+
7
+ describe('isDeepEqual', () => {
8
+ describe('primitives', () => {
9
+ it('returns true for identical primitives', () => {
10
+ expect(isDeepEqual(42, 42)).toBe(true)
11
+ expect(isDeepEqual('hello', 'hello')).toBe(true)
12
+ expect(isDeepEqual(true, true)).toBe(true)
13
+ expect(isDeepEqual(false, false)).toBe(true)
14
+ expect(isDeepEqual(null, null)).toBe(true)
15
+ expect(isDeepEqual(undefined, undefined)).toBe(true)
16
+ })
17
+
18
+ it('returns false for different primitives', () => {
19
+ expect(isDeepEqual(42, 43)).toBe(false)
20
+ expect(isDeepEqual('hello', 'world')).toBe(false)
21
+ expect(isDeepEqual(true, false)).toBe(false)
22
+ })
23
+
24
+ it('returns false for different types', () => {
25
+ expect(isDeepEqual(42, '42')).toBe(false)
26
+ expect(isDeepEqual(0, false)).toBe(false)
27
+ expect(isDeepEqual('', false)).toBe(false)
28
+ expect(isDeepEqual(null, undefined)).toBe(false)
29
+ })
30
+
31
+ it('handles NaN correctly', () => {
32
+ expect(isDeepEqual(Number.NaN, Number.NaN)).toBe(true)
33
+ expect(isDeepEqual(Number.NaN, 0)).toBe(false)
34
+ })
35
+
36
+ it('returns false when comparing null or undefined with other values', () => {
37
+ expect(isDeepEqual(null, 0)).toBe(false)
38
+ expect(isDeepEqual(undefined, 0)).toBe(false)
39
+ expect(isDeepEqual(null, '')).toBe(false)
40
+ expect(isDeepEqual(undefined, '')).toBe(false)
41
+ })
42
+ })
43
+
44
+ describe('arrays', () => {
45
+ it('returns true for identical arrays', () => {
46
+ expect(isDeepEqual([], [])).toBe(true)
47
+ expect(isDeepEqual([1, 2, 3], [1, 2, 3])).toBe(true)
48
+ expect(isDeepEqual(['a', 'b'], ['a', 'b'])).toBe(true)
49
+ })
50
+
51
+ it('returns false for arrays with different lengths', () => {
52
+ expect(isDeepEqual([1, 2], [1, 2, 3])).toBe(false)
53
+ expect(isDeepEqual([1], [])).toBe(false)
54
+ })
55
+
56
+ it('returns false for arrays with different values', () => {
57
+ expect(isDeepEqual([1, 2, 3], [1, 2, 4])).toBe(false)
58
+ expect(isDeepEqual(['a', 'b'], ['a', 'c'])).toBe(false)
59
+ })
60
+
61
+ it('handles nested arrays', () => {
62
+ expect(
63
+ isDeepEqual(
64
+ [
65
+ [1, 2],
66
+ [3, 4],
67
+ ],
68
+ [
69
+ [1, 2],
70
+ [3, 4],
71
+ ],
72
+ ),
73
+ ).toBe(true)
74
+ expect(
75
+ isDeepEqual(
76
+ [
77
+ [1, 2],
78
+ [3, 4],
79
+ ],
80
+ [
81
+ [1, 2],
82
+ [3, 5],
83
+ ],
84
+ ),
85
+ ).toBe(false)
86
+ })
87
+ })
88
+
89
+ describe('objects', () => {
90
+ it('returns true for identical objects', () => {
91
+ expect(isDeepEqual({}, {})).toBe(true)
92
+ expect(isDeepEqual({ a: 1, b: 2 }, { a: 1, b: 2 })).toBe(true)
93
+ })
94
+
95
+ it('returns false for objects with different keys', () => {
96
+ expect(isDeepEqual({ a: 1 }, { b: 1 })).toBe(false)
97
+ expect(isDeepEqual({ a: 1, b: 2 }, { a: 1 })).toBe(false)
98
+ })
99
+
100
+ it('returns false for objects with different values', () => {
101
+ expect(isDeepEqual({ a: 1 }, { a: 2 })).toBe(false)
102
+ expect(isDeepEqual({ a: 'hello' }, { a: 'world' })).toBe(false)
103
+ })
104
+
105
+ it('handles nested objects', () => {
106
+ expect(isDeepEqual({ a: { b: 1 } }, { a: { b: 1 } })).toBe(true)
107
+ expect(isDeepEqual({ a: { b: 1 } }, { a: { b: 2 } })).toBe(false)
108
+ })
109
+
110
+ it('handles objects with arrays', () => {
111
+ expect(isDeepEqual({ arr: [1, 2, 3] }, { arr: [1, 2, 3] })).toBe(true)
112
+ expect(isDeepEqual({ arr: [1, 2, 3] }, { arr: [1, 2, 4] })).toBe(false)
113
+ })
114
+ })
115
+
116
+ describe('Sets', () => {
117
+ it('returns true for identical sets', () => {
118
+ expect(isDeepEqual(new Set(), new Set())).toBe(true)
119
+ expect(isDeepEqual(new Set([1, 2, 3]), new Set([1, 2, 3]))).toBe(true)
120
+ expect(isDeepEqual(new Set(['a', 'b']), new Set(['a', 'b']))).toBe(true)
121
+ })
122
+
123
+ it('returns false for sets with different sizes', () => {
124
+ expect(isDeepEqual(new Set([1, 2]), new Set([1, 2, 3]))).toBe(false)
125
+ expect(isDeepEqual(new Set([1]), new Set())).toBe(false)
126
+ })
127
+
128
+ it('returns false for sets with different values', () => {
129
+ expect(isDeepEqual(new Set([1, 2, 3]), new Set([1, 2, 4]))).toBe(false)
130
+ expect(isDeepEqual(new Set(['a', 'b']), new Set(['a', 'c']))).toBe(false)
131
+ })
132
+
133
+ it('handles set order independence', () => {
134
+ expect(isDeepEqual(new Set([1, 2, 3]), new Set([3, 2, 1]))).toBe(true)
135
+ })
136
+ })
137
+
138
+ describe('Maps', () => {
139
+ it('returns true for identical maps', () => {
140
+ expect(isDeepEqual(new Map(), new Map())).toBe(true)
141
+ expect(
142
+ isDeepEqual(
143
+ new Map([
144
+ ['a', 1],
145
+ ['b', 2],
146
+ ]),
147
+ new Map([
148
+ ['a', 1],
149
+ ['b', 2],
150
+ ]),
151
+ ),
152
+ ).toBe(true)
153
+ })
154
+
155
+ it('returns false for maps with different sizes', () => {
156
+ expect(
157
+ isDeepEqual(
158
+ new Map([['a', 1]]),
159
+ new Map([
160
+ ['a', 1],
161
+ ['b', 2],
162
+ ]),
163
+ ),
164
+ ).toBe(false)
165
+ })
166
+
167
+ it('returns false for maps with different keys', () => {
168
+ expect(isDeepEqual(new Map([['a', 1]]), new Map([['b', 1]]))).toBe(false)
169
+ })
170
+
171
+ it('returns false for maps with different values', () => {
172
+ expect(isDeepEqual(new Map([['a', 1]]), new Map([['a', 2]]))).toBe(false)
173
+ })
174
+
175
+ it('handles nested values in maps', () => {
176
+ expect(
177
+ isDeepEqual(new Map([['a', { b: 1 }]]), new Map([['a', { b: 1 }]])),
178
+ ).toBe(true)
179
+ expect(
180
+ isDeepEqual(new Map([['a', { b: 1 }]]), new Map([['a', { b: 2 }]])),
181
+ ).toBe(false)
182
+ })
183
+
184
+ it('handles arrays as map values', () => {
185
+ expect(
186
+ isDeepEqual(new Map([['a', [1, 2, 3]]]), new Map([['a', [1, 2, 3]]])),
187
+ ).toBe(true)
188
+ expect(
189
+ isDeepEqual(new Map([['a', [1, 2, 3]]]), new Map([['a', [1, 2, 4]]])),
190
+ ).toBe(false)
191
+ })
192
+ })
193
+
194
+ describe('mixed types', () => {
195
+ it('returns false when comparing different collection types', () => {
196
+ expect(isDeepEqual([], {})).toBe(false)
197
+ expect(isDeepEqual(new Set(), new Map())).toBe(false)
198
+ expect(isDeepEqual(new Set([1, 2]), [1, 2])).toBe(false)
199
+ expect(isDeepEqual(new Map(), {})).toBe(false)
200
+ })
201
+
202
+ it('handles complex nested structures', () => {
203
+ const obj1 = {
204
+ arr: [1, 2, { nested: true }],
205
+ map: new Map([['key', [1, 2, 3]]]),
206
+ set: new Set([1, 2, 3]),
207
+ }
208
+ const obj2 = {
209
+ arr: [1, 2, { nested: true }],
210
+ map: new Map([['key', [1, 2, 3]]]),
211
+ set: new Set([1, 2, 3]),
212
+ }
213
+ const obj3 = {
214
+ arr: [1, 2, { nested: false }],
215
+ map: new Map([['key', [1, 2, 3]]]),
216
+ set: new Set([1, 2, 3]),
217
+ }
218
+
219
+ expect(isDeepEqual(obj1, obj2)).toBe(true)
220
+ expect(isDeepEqual(obj1, obj3)).toBe(false)
221
+ })
222
+ })
223
+ })
@@ -0,0 +1,95 @@
1
+ import { isMap, isSet } from './checker'
2
+
3
+ /**
4
+ * Whether two values are deeply equal.
5
+ */
6
+ export function isDeepEqual(a: unknown, b: unknown): boolean {
7
+ if (a === b) {
8
+ return true
9
+ }
10
+
11
+ // Handle null and undefined early
12
+ if (a == null || b == null) {
13
+ return false
14
+ }
15
+
16
+ const aType = typeof a
17
+ const bType = typeof b
18
+ if (aType !== bType) {
19
+ return false
20
+ }
21
+
22
+ if (aType === 'number' && Number.isNaN(a) && Number.isNaN(b)) {
23
+ return true
24
+ }
25
+
26
+ if (Array.isArray(a)) {
27
+ if (!Array.isArray(b)) {
28
+ return false
29
+ }
30
+ if (a.length !== b.length) {
31
+ return false
32
+ }
33
+ const size = a.length
34
+ for (let i = 0; i < size; i++) {
35
+ if (!isDeepEqual(a[i], b[i])) {
36
+ return false
37
+ }
38
+ }
39
+ return true
40
+ }
41
+
42
+ if (isSet(a)) {
43
+ if (!isSet(b)) {
44
+ return false
45
+ }
46
+ if (a.size !== b.size) {
47
+ return false
48
+ }
49
+ for (const value of a) {
50
+ if (!b.has(value)) {
51
+ return false
52
+ }
53
+ }
54
+ return true
55
+ }
56
+
57
+ if (isMap(a)) {
58
+ if (!isMap(b)) {
59
+ return false
60
+ }
61
+ if (a.size !== b.size) {
62
+ return false
63
+ }
64
+ for (const key of a.keys()) {
65
+ if (!b.has(key)) {
66
+ return false
67
+ }
68
+ if (!isDeepEqual(a.get(key), b.get(key))) {
69
+ return false
70
+ }
71
+ }
72
+ return true
73
+ }
74
+
75
+ if (typeof a === 'object' && typeof b === 'object') {
76
+ const aKeys = Object.keys(a)
77
+ const bKeys = Object.keys(b)
78
+ if (aKeys.length !== bKeys.length) {
79
+ return false
80
+ }
81
+ for (const key of aKeys) {
82
+ if (
83
+ !isDeepEqual(
84
+ (a as Record<string, unknown>)[key],
85
+ (b as Record<string, unknown>)[key],
86
+ )
87
+ ) {
88
+ return false
89
+ }
90
+ }
91
+ return true
92
+ }
93
+
94
+ return false
95
+ }
@@ -0,0 +1,78 @@
1
+ import { describe, it, expect } from 'vitest'
2
+
3
+ import {
4
+ mapGroupBy,
5
+ mapGroupByPolyfill,
6
+ mapGroupByNative,
7
+ } from './map-group-by'
8
+
9
+ const testCases = [
10
+ { name: 'mapGroupBy', fn: mapGroupBy },
11
+ { name: 'mapGroupByPolyfill', fn: mapGroupByPolyfill },
12
+ ]
13
+
14
+ if (!!Map.groupBy) {
15
+ testCases.push({ name: 'mapGroupByNative', fn: mapGroupByNative })
16
+ }
17
+
18
+ describe.each(testCases)('$name', ({ fn }) => {
19
+ it('groups items by key', () => {
20
+ const items = [1, 2, 3, 4, 5, 6]
21
+ const result = fn(items, (item) => item % 2)
22
+
23
+ expect(result.get(0)).toEqual([2, 4, 6])
24
+ expect(result.get(1)).toEqual([1, 3, 5])
25
+ })
26
+
27
+ it('works with string keys', () => {
28
+ const items = ['apple', 'banana', 'apricot', 'blueberry']
29
+ const result = fn(items, (item) => item[0])
30
+
31
+ expect(result.get('a')).toEqual(['apple', 'apricot'])
32
+ expect(result.get('b')).toEqual(['banana', 'blueberry'])
33
+ })
34
+
35
+ it('works with object keys', () => {
36
+ const keyA = { type: 'A' }
37
+ const keyB = { type: 'B' }
38
+ const items = [1, 2, 3, 4]
39
+ const result = fn(items, (item) => (item % 2 === 0 ? keyA : keyB))
40
+
41
+ expect(result.get(keyA)).toEqual([2, 4])
42
+ expect(result.get(keyB)).toEqual([1, 3])
43
+ })
44
+
45
+ it('passes index to key selector', () => {
46
+ const items = ['a', 'b', 'c', 'd']
47
+ const result = fn(items, (_, index) => Math.floor(index / 2))
48
+
49
+ expect(result.get(0)).toEqual(['a', 'b'])
50
+ expect(result.get(1)).toEqual(['c', 'd'])
51
+ })
52
+
53
+ it('handles empty array', () => {
54
+ const result = fn([], (item) => item)
55
+ expect(result.size).toBe(0)
56
+ })
57
+
58
+ it('handles single item', () => {
59
+ const result = fn([42], (item) => item)
60
+ expect(result.get(42)).toEqual([42])
61
+ })
62
+
63
+ it('handles all items mapping to same key', () => {
64
+ const items = [1, 2, 3, 4]
65
+ const result = fn(items, () => 'same')
66
+
67
+ expect(result.size).toBe(1)
68
+ expect(result.get('same')).toEqual([1, 2, 3, 4])
69
+ })
70
+
71
+ it('works with iterables other than arrays', () => {
72
+ const set = new Set([1, 2, 3, 4, 5])
73
+ const result = fn(set, (item) => item % 2)
74
+
75
+ expect(result.get(0)).toEqual([2, 4])
76
+ expect(result.get(1)).toEqual([1, 3, 5])
77
+ })
78
+ })
@@ -0,0 +1,41 @@
1
+ /**
2
+ * @internal
3
+ */
4
+ export function mapGroupByPolyfill<K, T>(
5
+ items: Iterable<T>,
6
+ keySelector: (item: T, index: number) => K,
7
+ ): Map<K, T[]> {
8
+ const map = new Map<K, T[]>()
9
+ let index = 0
10
+ for (const item of items) {
11
+ const key = keySelector(item, index)
12
+ const group = map.get(key)
13
+ if (group) {
14
+ group.push(item)
15
+ } else {
16
+ map.set(key, [item])
17
+ }
18
+ index++
19
+ }
20
+ return map
21
+ }
22
+
23
+ /**
24
+ * @internal
25
+ */
26
+ export function mapGroupByNative<K, T>(
27
+ items: Iterable<T>,
28
+ keySelector: (item: T, index: number) => K,
29
+ ): Map<K, T[]> {
30
+ return Map.groupBy(items, keySelector)
31
+ }
32
+
33
+ /**
34
+ * A polyfill for the `Map.groupBy` static method.
35
+ *
36
+ * @public
37
+ */
38
+ export const mapGroupBy: <K, T>(
39
+ items: Iterable<T>,
40
+ keySelector: (item: T, index: number) => K,
41
+ ) => Map<K, T[]> = !!Map.groupBy ? mapGroupByNative : mapGroupByPolyfill
@@ -0,0 +1,86 @@
1
+ import { describe, it, expect } from 'vitest'
2
+
3
+ import {
4
+ objectGroupBy,
5
+ objectGroupByPolyfill,
6
+ objectGroupByNative,
7
+ } from './object-group-by'
8
+
9
+ const testCases = [
10
+ { name: 'objectGroupBy', fn: objectGroupBy },
11
+ { name: 'objectGroupByPolyfill', fn: objectGroupByPolyfill },
12
+ ]
13
+
14
+ if (!!Object.groupBy) {
15
+ testCases.push({ name: 'objectGroupByNative', fn: objectGroupByNative })
16
+ }
17
+
18
+ describe.each(testCases)('$name', ({ fn }) => {
19
+ it('groups items by key', () => {
20
+ const items = [1, 2, 3, 4, 5, 6]
21
+ const result = fn(items, (item) => (item % 2 === 0 ? 'even' : 'odd'))
22
+
23
+ expect(result.even).toEqual([2, 4, 6])
24
+ expect(result.odd).toEqual([1, 3, 5])
25
+ })
26
+
27
+ it('works with string keys', () => {
28
+ const items = ['apple', 'banana', 'apricot', 'blueberry']
29
+ const result = fn(items, (item) => item[0])
30
+
31
+ expect(result.a).toEqual(['apple', 'apricot'])
32
+ expect(result.b).toEqual(['banana', 'blueberry'])
33
+ })
34
+
35
+ it('works with number keys', () => {
36
+ const items = ['a', 'b', 'c', 'd']
37
+ const result = fn(items, (_, index) => Math.floor(index / 2))
38
+
39
+ expect(result[0]).toEqual(['a', 'b'])
40
+ expect(result[1]).toEqual(['c', 'd'])
41
+ })
42
+
43
+ it('works with symbol keys', () => {
44
+ const symA = Symbol('A')
45
+ const symB = Symbol('B')
46
+ const items = [1, 2, 3, 4]
47
+ const result = fn(items, (item) => (item % 2 === 0 ? symA : symB))
48
+
49
+ expect(result[symA]).toEqual([2, 4])
50
+ expect(result[symB]).toEqual([1, 3])
51
+ })
52
+
53
+ it('passes index to key selector', () => {
54
+ const items = ['a', 'b', 'c', 'd']
55
+ const result = fn(items, (_, index) => (index < 2 ? 'first' : 'second'))
56
+
57
+ expect(result.first).toEqual(['a', 'b'])
58
+ expect(result.second).toEqual(['c', 'd'])
59
+ })
60
+
61
+ it('handles empty array', () => {
62
+ const result = fn([], (item) => String(item))
63
+ expect(Object.keys(result)).toHaveLength(0)
64
+ })
65
+
66
+ it('handles single item', () => {
67
+ const result = fn([42], (item) => String(item))
68
+ expect(result['42']).toEqual([42])
69
+ })
70
+
71
+ it('handles all items mapping to same key', () => {
72
+ const items = [1, 2, 3, 4]
73
+ const result = fn(items, () => 'same')
74
+
75
+ expect(Object.keys(result)).toHaveLength(1)
76
+ expect(result.same).toEqual([1, 2, 3, 4])
77
+ })
78
+
79
+ it('works with iterables other than arrays', () => {
80
+ const set = new Set([1, 2, 3, 4, 5])
81
+ const result = fn(set, (item) => (item % 2 === 0 ? 'even' : 'odd'))
82
+
83
+ expect(result.even).toEqual([2, 4])
84
+ expect(result.odd).toEqual([1, 3, 5])
85
+ })
86
+ })
@@ -0,0 +1,43 @@
1
+ /**
2
+ * @internal
3
+ */
4
+ export function objectGroupByPolyfill<K extends PropertyKey, T>(
5
+ items: Iterable<T>,
6
+ keySelector: (item: T, index: number) => K,
7
+ ): Partial<Record<K, T[]>> {
8
+ const result: Partial<Record<K, T[]>> = {}
9
+ let index = 0
10
+ for (const item of items) {
11
+ const key = keySelector(item, index)
12
+ const group = result[key]
13
+ if (group) {
14
+ group.push(item)
15
+ } else {
16
+ result[key] = [item]
17
+ }
18
+ index++
19
+ }
20
+ return result
21
+ }
22
+
23
+ /**
24
+ * @internal
25
+ */
26
+ export function objectGroupByNative<K extends PropertyKey, T>(
27
+ items: Iterable<T>,
28
+ keySelector: (item: T, index: number) => K,
29
+ ): Partial<Record<K, T[]>> {
30
+ return Object.groupBy(items, keySelector)
31
+ }
32
+
33
+ /**
34
+ * A polyfill for the `Object.groupBy` static method.
35
+ *
36
+ * @public
37
+ */
38
+ export const objectGroupBy: <K extends PropertyKey, T>(
39
+ items: Iterable<T>,
40
+ keySelector: (item: T, index: number) => K,
41
+ ) => Partial<Record<K, T[]>> = !!Object.groupBy
42
+ ? objectGroupByNative
43
+ : objectGroupByPolyfill