@ocavue/utils 0.8.1 → 0.9.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 +13 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +21 -1
- package/dist/index.js.map +1 -1
- package/package.json +10 -8
- package/src/default-map.test.ts +183 -0
- package/src/default-map.ts +22 -0
- package/src/index.ts +1 -0
package/dist/index.d.ts
CHANGED
|
@@ -100,5 +100,17 @@ declare function once<T>(fn: () => T): () => T;
|
|
|
100
100
|
*/
|
|
101
101
|
declare function sleep(ms: number): Promise<void>;
|
|
102
102
|
//#endregion
|
|
103
|
-
|
|
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 };
|
|
104
116
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -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"],"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,
|
|
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;AAWgB,iBAxDA,YAAA,CAwDuC,IAAM,EAxD1B,IAwD0B,CAAA,EAAA,IAAA,IAxDX,UAwDW;AAQ7D;;;AAC+B,iBA1Df,eAAA,CA0De,IAAA,EA1DO,IA0DP,CAAA,EAAA,IAAA,IA1DsB,aA0DtB;;;;AAoBf,iBApEA,UAAA,CAoEW,IAAA,EApEM,IAoEN,CAAA,EAAA,IAAA,IApEqB,QAoErB;;;;AACU,iBA9DrB,kBAAA,CA8DqB,IAAA,EA9DI,IA8DJ,CAAA,EAAA,IAAA,IA9DmB,gBA8DnB;;;AAiBrC;AACW,iBAzEK,YAAA,CAyEL,IAAA,EAzEwB,IAyExB,CAAA,EAAA,IAAA,IAzEuC,UAyEvC;;;;AACR,iBAnEa,UAAA,CAmEb,KAAA,EAAA,OAAA,CAAA,EAAA,KAAA,IAnEkD,IAmElD;;;;iBA5Da,aAAA,2BAAwC;ACnExD;;;iBD8EgB,YAAA,2BAAuC;AE9EvD;;;;ACQgB,iBH8EA,SAAA,CG9E6B,MAAA,CAAA,EH+ElC,IG/EkC,GH+E3B,UG/E2B,GH+Ed,QG/Ec,GAAA,IAAA,CAAA,EHgF1C,MGhF0C,GAAA,OHgF1B,UGhF0B;;;;ACV7C;iBJ6GgB,WAAA,UACL,UAAU,SAAS,OAAO,kBAClC;;;AK7GH;AAA0C,iBL6H1B,kBAAA,CK7H0B,MAAA,CAAA,EL8H/B,OK9H+B,GL8HrB,IK9HqB,GL8Hd,MK9Hc,GL8HL,QK9HK,GAAA,IAAA,CAAA,EL+HvC,WK/HuC;;;;ANF1C;;;;ACGgB,iBCDA,WAAA,CDC+B,KAAO,EAAA,MAAA,CAAA,EAAA,MAAA;;;;ADHtD;;iBGEgB,KAAA,CAAA;;;;AHFhB;;;;ACGA;AAOA;AAOA;AAOA;AAOA;AAUA;AAOA;AAOA;AAOgB,iBGpDA,IHoDU,CAA2B,CAAA,CAAA,CAAA,EAAI,EAAA,GAAA,GGpDvB,CHoDuB,CAAA,EAAA,GAAA,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"}
|
package/dist/index.js
CHANGED
|
@@ -185,5 +185,25 @@ function sleep(ms) {
|
|
|
185
185
|
}
|
|
186
186
|
|
|
187
187
|
//#endregion
|
|
188
|
-
|
|
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 };
|
|
189
209
|
//# 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"],"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"],"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;AACjE,QACE,UAAU,KAAK,IACf,KAAK,iBAAiB;;;;;AAO1B,SAAgB,WAAW,MAA8B;AACvD,QAAO,KAAK,aAAaC;;;;;AAM3B,SAAgB,mBAAmB,MAAsC;AACvE,QAAO,KAAK,aAAaC;;;;;AAM3B,SAAgB,aAAa,MAAgC;AAC3D,QAAO,mBAAmB,KAAK,IAAI,UAAU,QAAQ,cAAc,KAAK,KAAK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AAI;AACb,YAAS;AAET,QAAK;;AAEP,SAAO;;;;;;;;;ACpBX,SAAgB,MAAM,IAA2B;AAC/C,QAAO,IAAI,SAAS,YAAY,WAAW,SAAS,GAAG,CAAC"}
|
|
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;AACjE,QACE,UAAU,KAAK,IACf,KAAK,iBAAiB;;;;;AAO1B,SAAgB,WAAW,MAA8B;AACvD,QAAO,KAAK,aAAaC;;;;;AAM3B,SAAgB,mBAAmB,MAAsC;AACvE,QAAO,KAAK,aAAaC;;;;;AAM3B,SAAgB,aAAa,MAAgC;AAC3D,QAAO,mBAAmB,KAAK,IAAI,UAAU,QAAQ,cAAc,KAAK,KAAK;;;;;AAM/E,SAAgB,WAAW,OAA+B;AACxD,QAAO,SAAS,MAAM,IAAI,MAAM,aAAa;;;;;AAM/C,SAAgB,cAAc,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,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"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ocavue/utils",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.9.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",
|
|
@@ -37,19 +37,20 @@
|
|
|
37
37
|
"dist"
|
|
38
38
|
],
|
|
39
39
|
"devDependencies": {
|
|
40
|
-
"@ocavue/eslint-config": "^3.6.
|
|
41
|
-
"@ocavue/tsconfig": "^0.
|
|
40
|
+
"@ocavue/eslint-config": "^3.6.2",
|
|
41
|
+
"@ocavue/tsconfig": "^0.6.1",
|
|
42
42
|
"@size-limit/preset-small-lib": "^11.2.0",
|
|
43
43
|
"@types/node": "^24.9.2",
|
|
44
|
-
"@vitest/coverage-v8": "4.0.
|
|
44
|
+
"@vitest/coverage-v8": "4.0.13",
|
|
45
45
|
"eslint": "^9.38.0",
|
|
46
|
-
"jsdom": "^27.0
|
|
46
|
+
"jsdom": "^27.2.0",
|
|
47
|
+
"pkg-pr-new": "^0.0.60",
|
|
47
48
|
"prettier": "^3.6.2",
|
|
48
49
|
"size-limit": "^11.2.0",
|
|
49
|
-
"tsdown": "^0.
|
|
50
|
+
"tsdown": "^0.16.6",
|
|
50
51
|
"typescript": "^5.9.3",
|
|
51
|
-
"vite": "^7.
|
|
52
|
-
"vitest": "^4.0.
|
|
52
|
+
"vite": "^7.2.4",
|
|
53
|
+
"vitest": "^4.0.13"
|
|
53
54
|
},
|
|
54
55
|
"publishConfig": {
|
|
55
56
|
"access": "public"
|
|
@@ -69,6 +70,7 @@
|
|
|
69
70
|
"dev": "tsdown --watch",
|
|
70
71
|
"lint": "eslint .",
|
|
71
72
|
"fix": "eslint --fix . && prettier --write .",
|
|
73
|
+
"ci:publish:snapshot": "pkg-pr-new publish --pnpm",
|
|
72
74
|
"test": "vitest",
|
|
73
75
|
"typecheck": "tsc -b"
|
|
74
76
|
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
// @vitest-environment node
|
|
2
|
+
|
|
3
|
+
import { describe, it, expect } from 'vitest'
|
|
4
|
+
|
|
5
|
+
import { DefaultMap } from './default-map'
|
|
6
|
+
|
|
7
|
+
describe('DefaultMap', () => {
|
|
8
|
+
it('creates default values for missing keys', () => {
|
|
9
|
+
const map = new DefaultMap<string, number>(() => 0)
|
|
10
|
+
|
|
11
|
+
expect(map.get('key1')).toBe(0)
|
|
12
|
+
expect(map.get('key2')).toBe(0)
|
|
13
|
+
})
|
|
14
|
+
|
|
15
|
+
it('returns existing values for set keys', () => {
|
|
16
|
+
const map = new DefaultMap<string, number>(() => 0)
|
|
17
|
+
|
|
18
|
+
map.set('key1', 42)
|
|
19
|
+
expect(map.get('key1')).toBe(42)
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
it('stores the default value when accessing missing key', () => {
|
|
23
|
+
const map = new DefaultMap<string, number>(() => 5)
|
|
24
|
+
|
|
25
|
+
const value = map.get('key1')
|
|
26
|
+
expect(value).toBe(5)
|
|
27
|
+
expect(map.has('key1')).toBe(true)
|
|
28
|
+
expect(map.get('key1')).toBe(5)
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('works with array factory', () => {
|
|
32
|
+
const map = new DefaultMap<string, string[]>(() => [])
|
|
33
|
+
|
|
34
|
+
map.get('key1').push('item1')
|
|
35
|
+
map.get('key1').push('item2')
|
|
36
|
+
map.get('key2').push('item3')
|
|
37
|
+
|
|
38
|
+
expect(map.get('key1')).toEqual(['item1', 'item2'])
|
|
39
|
+
expect(map.get('key2')).toEqual(['item3'])
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
it('works with object factory', () => {
|
|
43
|
+
const map = new DefaultMap<string, { count: number }>(() => ({
|
|
44
|
+
count: 0,
|
|
45
|
+
}))
|
|
46
|
+
|
|
47
|
+
map.get('key1').count += 1
|
|
48
|
+
map.get('key1').count += 1
|
|
49
|
+
map.get('key2').count += 5
|
|
50
|
+
|
|
51
|
+
expect(map.get('key1').count).toBe(2)
|
|
52
|
+
expect(map.get('key2').count).toBe(5)
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
it('accepts initial entries via array', () => {
|
|
56
|
+
const initialEntries: [string, number][] = [
|
|
57
|
+
['a', 1],
|
|
58
|
+
['b', 2],
|
|
59
|
+
['c', 3],
|
|
60
|
+
]
|
|
61
|
+
const map = new DefaultMap<string, number>(() => 0, initialEntries)
|
|
62
|
+
|
|
63
|
+
expect(map.get('a')).toBe(1)
|
|
64
|
+
expect(map.get('b')).toBe(2)
|
|
65
|
+
expect(map.get('c')).toBe(3)
|
|
66
|
+
expect(map.get('d')).toBe(0)
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
it('accepts initial entries via non-array iterable', () => {
|
|
70
|
+
const existingMap = new Map<string, number>([
|
|
71
|
+
['x', 10],
|
|
72
|
+
['y', 20],
|
|
73
|
+
['z', 30],
|
|
74
|
+
])
|
|
75
|
+
const map = new DefaultMap<string, number>(() => 0, existingMap)
|
|
76
|
+
|
|
77
|
+
expect(map.get('x')).toBe(10)
|
|
78
|
+
expect(map.get('y')).toBe(20)
|
|
79
|
+
expect(map.get('z')).toBe(30)
|
|
80
|
+
expect(map.get('w')).toBe(0)
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
it('calls factory function only when key is missing', () => {
|
|
84
|
+
let callCount = 0
|
|
85
|
+
const map = new DefaultMap<string, number>(() => {
|
|
86
|
+
callCount++
|
|
87
|
+
return 42
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
map.set('existing', 100)
|
|
91
|
+
|
|
92
|
+
map.get('existing')
|
|
93
|
+
expect(callCount).toBe(0)
|
|
94
|
+
|
|
95
|
+
map.get('new')
|
|
96
|
+
expect(callCount).toBe(1)
|
|
97
|
+
|
|
98
|
+
map.get('new')
|
|
99
|
+
expect(callCount).toBe(1)
|
|
100
|
+
|
|
101
|
+
map.get('another')
|
|
102
|
+
expect(callCount).toBe(2)
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
it('works with size property', () => {
|
|
106
|
+
const map = new DefaultMap<string, number>(() => 0)
|
|
107
|
+
|
|
108
|
+
expect(map.size).toBe(0)
|
|
109
|
+
|
|
110
|
+
map.get('key1')
|
|
111
|
+
expect(map.size).toBe(1)
|
|
112
|
+
|
|
113
|
+
map.get('key2')
|
|
114
|
+
expect(map.size).toBe(2)
|
|
115
|
+
|
|
116
|
+
map.get('key1')
|
|
117
|
+
expect(map.size).toBe(2)
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
it('works with delete method', () => {
|
|
121
|
+
const map = new DefaultMap<string, number>(() => 10)
|
|
122
|
+
|
|
123
|
+
map.get('key1')
|
|
124
|
+
expect(map.has('key1')).toBe(true)
|
|
125
|
+
|
|
126
|
+
map.delete('key1')
|
|
127
|
+
expect(map.has('key1')).toBe(false)
|
|
128
|
+
|
|
129
|
+
const value = map.get('key1')
|
|
130
|
+
expect(value).toBe(10)
|
|
131
|
+
expect(map.has('key1')).toBe(true)
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
it('works with clear method', () => {
|
|
135
|
+
const map = new DefaultMap<string, number>(() => 0)
|
|
136
|
+
|
|
137
|
+
map.get('key1')
|
|
138
|
+
map.get('key2')
|
|
139
|
+
expect(map.size).toBe(2)
|
|
140
|
+
|
|
141
|
+
map.clear()
|
|
142
|
+
expect(map.size).toBe(0)
|
|
143
|
+
expect(map.has('key1')).toBe(false)
|
|
144
|
+
})
|
|
145
|
+
|
|
146
|
+
it('works with iteration methods', () => {
|
|
147
|
+
const map = new DefaultMap<string, number>(() => 0, [
|
|
148
|
+
['a', 1],
|
|
149
|
+
['b', 2],
|
|
150
|
+
])
|
|
151
|
+
|
|
152
|
+
expect([...map.keys()]).toEqual(['a', 'b'])
|
|
153
|
+
expect([...map.values()]).toEqual([1, 2])
|
|
154
|
+
expect([...map.entries()]).toEqual([
|
|
155
|
+
['a', 1],
|
|
156
|
+
['b', 2],
|
|
157
|
+
])
|
|
158
|
+
})
|
|
159
|
+
|
|
160
|
+
it('creates independent default values', () => {
|
|
161
|
+
const map = new DefaultMap<string, number[]>(() => [])
|
|
162
|
+
|
|
163
|
+
map.get('key1').push(1)
|
|
164
|
+
map.get('key2').push(2)
|
|
165
|
+
|
|
166
|
+
expect(map.get('key1')).toEqual([1])
|
|
167
|
+
expect(map.get('key2')).toEqual([2])
|
|
168
|
+
})
|
|
169
|
+
|
|
170
|
+
it('works with nested DefaultMaps', () => {
|
|
171
|
+
const map = new DefaultMap<string, DefaultMap<string, number>>(
|
|
172
|
+
() => new DefaultMap<string, number>(() => 0),
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
map.get('group1').get('item1')
|
|
176
|
+
map.get('group1').set('item2', 5)
|
|
177
|
+
map.get('group2').get('item1')
|
|
178
|
+
|
|
179
|
+
expect(map.get('group1').get('item1')).toBe(0)
|
|
180
|
+
expect(map.get('group1').get('item2')).toBe(5)
|
|
181
|
+
expect(map.get('group2').get('item1')).toBe(0)
|
|
182
|
+
})
|
|
183
|
+
})
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A map that automatically creates values for missing keys using a factory function.
|
|
3
|
+
*
|
|
4
|
+
* Similar to Python's [defaultdict](https://docs.python.org/3.13/library/collections.html#collections.defaultdict).
|
|
5
|
+
*/
|
|
6
|
+
export class DefaultMap<K, V> extends Map<K, V> {
|
|
7
|
+
private readonly defaultFactory: () => V
|
|
8
|
+
|
|
9
|
+
constructor(defaultFactory: () => V, iterable?: Iterable<readonly [K, V]>) {
|
|
10
|
+
super(iterable)
|
|
11
|
+
this.defaultFactory = defaultFactory
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
override get(key: K): V {
|
|
15
|
+
if (this.has(key)) {
|
|
16
|
+
return super.get(key)!
|
|
17
|
+
}
|
|
18
|
+
const value = this.defaultFactory()
|
|
19
|
+
this.set(key, value)
|
|
20
|
+
return value
|
|
21
|
+
}
|
|
22
|
+
}
|
package/src/index.ts
CHANGED