@inox-tools/utils 0.2.0 → 0.3.0-beta.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/lazy.js +1 -4
- package/dist/once.js +1 -4
- package/dist/types.js +0 -1
- package/dist/unist/visit.js +1 -6
- package/dist/unist/visit.js.map +1 -1
- package/dist/values.d.ts +35 -1
- package/dist/values.js +1 -4
- package/dist/values.js.map +1 -1
- package/package.json +10 -10
- package/src/values.ts +92 -0
package/dist/lazy.js
CHANGED
|
@@ -1,5 +1,2 @@
|
|
|
1
|
-
class a{constructor(i){this.factory=i;}initialized=!1;value;static of(i){return new this(i)}get(){return this.initialized||(this.value=this.factory(),this.initialized=!0),this.value}}
|
|
2
|
-
|
|
3
|
-
export { a as Lazy };
|
|
4
|
-
//# sourceMappingURL=lazy.js.map
|
|
1
|
+
class a{constructor(i){this.factory=i;}initialized=!1;value;static of(i){return new this(i)}get(){return this.initialized||(this.value=this.factory(),this.initialized=!0),this.value}}export{a as Lazy};//# sourceMappingURL=lazy.js.map
|
|
5
2
|
//# sourceMappingURL=lazy.js.map
|
package/dist/once.js
CHANGED
|
@@ -1,5 +1,2 @@
|
|
|
1
|
-
class o{#i=!1;do(i){this.#i||(i(),this.#i=!0);}async doAsync(i){this.#i||(await i(),this.#i=!0);}}
|
|
2
|
-
|
|
3
|
-
export { o as Once };
|
|
4
|
-
//# sourceMappingURL=once.js.map
|
|
1
|
+
class o{#i=!1;do(i){this.#i||(i(),this.#i=!0);}async doAsync(i){this.#i||(await i(),this.#i=!0);}}export{o as Once};//# sourceMappingURL=once.js.map
|
|
5
2
|
//# sourceMappingURL=once.js.map
|
package/dist/types.js
CHANGED
package/dist/unist/visit.js
CHANGED
|
@@ -1,7 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
const a=[],A=!0,f=!1,P="skip";function M({tree:e,test:u,enter:l,leave:c,reverse:p}){if(!e)throw new TypeError("A tree is required");if(!l&&!c)throw new Error("At least one visitor (`enter` or `leave`) must be provided");const I=convert(u),x=p?-1:1;h(e,void 0,[])();function h(n,k,s){const d=n;if(typeof d.type=="string"){const t=typeof d.tagName=="string"?d.tagName:typeof d.name=="string"?d.name:void 0;Object.defineProperty(y,"name",{value:"node ("+n.type+(t?"<"+t+">":"")+")"});}return y;function y(){let t=a,o,i,T;const m=!u||I(n,k,s[s.length-1]);if(m&&(t=C(l?.(n,s)),t[0]===f))return t;if("children"in n&&n.children){const r=n;if(r.children&&t[0]!==P)for(i=(p?r.children.length:-1)+x,T=s.concat(r);i>-1&&i<r.children.length;){const N=r.children[i];if(o=h(N,i,T)(),o[0]===f)return o;i=typeof o[1]=="number"?o[1]:i+x;}}if(m&&c){const r=C(c(n,s));return r===a?t:r}return t}}}function C(e){return Array.isArray(e)?e:typeof e=="number"?[A,e]:e==null?a:[e]}
|
|
4
|
-
|
|
5
|
-
export { A as CONTINUE, f as EXIT, P as SKIP, M as visitParents };
|
|
6
|
-
//# sourceMappingURL=visit.js.map
|
|
1
|
+
import {convert}from'unist-util-is';const a=[],A=!0,f=!1,P="skip";function M({tree:e,test:u,enter:l,leave:c,reverse:p}){if(!e)throw new TypeError("A tree is required");if(!l&&!c)throw new Error("At least one visitor (`enter` or `leave`) must be provided");const I=convert(u),x=p?-1:1;h(e,void 0,[])();function h(n,k,s){const d=n;if(typeof d.type=="string"){const t=typeof d.tagName=="string"?d.tagName:typeof d.name=="string"?d.name:void 0;Object.defineProperty(y,"name",{value:"node ("+n.type+(t?"<"+t+">":"")+")"});}return y;function y(){let t=a,o,i,T;const m=!u||I(n,k,s[s.length-1]);if(m&&(t=C(l?.(n,s)),t[0]===f))return t;if("children"in n&&n.children){const r=n;if(r.children&&t[0]!==P)for(i=(p?r.children.length:-1)+x,T=s.concat(r);i>-1&&i<r.children.length;){const N=r.children[i];if(o=h(N,i,T)(),o[0]===f)return o;i=typeof o[1]=="number"?o[1]:i+x;}}if(m&&c){const r=C(c(n,s));return r===a?t:r}return t}}}function C(e){return Array.isArray(e)?e:typeof e=="number"?[A,e]:e==null?a:[e]}export{A as CONTINUE,f as EXIT,P as SKIP,M as visitParents};//# sourceMappingURL=visit.js.map
|
|
7
2
|
//# sourceMappingURL=visit.js.map
|
package/dist/unist/visit.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/unist/visit.ts"],"names":["empty","CONTINUE","EXIT","SKIP","visitParents","tree","test","enterVisitor","leaveVisitor","reverse","is","convert","step","factory","node","index","parents","value","name","visit","result","subresult","offset","grandparents","isMatch","toResult","nodeAsParent","child","leaveResult"],"mappings":";;AAEA,MAAMA,CAAqB,CAAA,EAKdC,CAAAA,CAAAA,CAAW,CAKXC,CAAAA,CAAAA,CAAAA,CAAO,CAKPC,CAAAA,CAAAA,CAAAA,CAAO,OAUb,SAASC,CAAoE,CAAA,CACnF,IAAAC,CAAAA,CAAAA,CACA,IAAAC,CAAAA,CAAAA,CACA,KAAOC,CAAAA,CAAAA,CACP,KAAOC,CAAAA,CAAAA,CACP,OAAAC,CAAAA,CACD,CAAyB,CAAA,CACxB,GAAI,CAACJ,CAAAA,CACJ,MAAM,IAAI,SAAU,CAAA,oBAAoB,CAGzC,CAAA,GAAI,CAACE,CAAAA,EAAgB,CAACC,CAAAA,CACrB,MAAM,IAAI,KAAM,CAAA,4DAA4D,CAG7E,CAAA,MAAME,CAAKC,CAAAA,OAAAA,CAAQL,CAAI,CAAA,CAKjBM,CAAOH,CAAAA,CAAAA,CAAU,CAAK,CAAA,CAAA,CAAA,CAE5BI,CAAQR,CAAAA,CAAAA,CAAM,KAAW,CAAA,CAAA,EAAE,CAAA,GAE3B,SAASQ,CAAAA,CAAQC,CAAiBC,CAAAA,CAAAA,CAA2BC,CAAwB,CAAA,CACpF,MAAMC,CAAAA,CAAQH,CAEd,CAAA,GAAI,OAAOG,CAAAA,CAAM,IAAS,EAAA,QAAA,CAAU,CACnC,MAAMC,CAEL,CAAA,OAAOD,CAA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AAa,CAAA,QAAA,CAASJ,CAAM,CAAA,CAI1C,GAFAD,CAAAA,CAAYR,CAAQc,CAAAA,CAAAA,CAAOL,EAAQC,CAAY,CAAA,EAE3CF,CAAAA,CAAAA,CAAU,CAAC,CAAA,GAAMnB,CACpB,CAAA,OAAOmB,CAGRC,CAAAA,CAAAA,CAAS,OAAOD,CAAAA,CAAU,CAAC,CAAA,EAAM,QAAWA,CAAAA,CAAAA,CAAU,CAAC,CAAA,CAAIC,CAASV,CAAAA,EACrE,CAEF,CAEA,GAAIY,CAAAA,EAAWhB,CAAc,CAAA,CAC5B,MAAMoB,CAAAA,CAAcH,CACnBjB,CAAAA,CAAAA,CACCM,CACAE,CAAAA,CACD,CACD,CAEA,CAAA,OAAOY,CAAgB5B,GAAAA,CAAAA,CAAQoB,CAASQ,CAAAA,CACzC,CAEA,OAAOR,CACR,CACD,CACD,CAKA,SAASK,CAAAA,CAASR,CAA6C,CAAA,CAC9D,OAAI,KAAM,CAAA,OAAA,CAAQA,CAAK,CAAA,CACfA,CAGJ,CAAA,OAAOA,CAAU,EAAA,QAAA,CACb,CAAChB,CAAAA,CAAUgB,CAAK,CAAA,CAGjBA,CAAU,EAAA,IAAA,CAA8BjB,CAAQ,CAAA,CAACiB,CAAK,CAC9D","file":"visit.js","sourcesContent":["import { convert } from 'unist-util-is';\n\nconst empty: ActionTuple = [];\n\n/**\n * Continue traversing as normal.\n */\nexport const CONTINUE = true;\n\n/**\n * Stop traversing immediately.\n */\nexport const EXIT = false;\n\n/**\n * Do not traverse this node’s children.\n */\nexport const SKIP = 'skip';\n\nexport type Options<Tree extends import('unist').Node, Check extends Test> = {\n\ttree: Tree;\n\ttest?: Check;\n\tenter?: BuildVisitor<Tree, Check>;\n\tleave?: BuildVisitor<Tree, Check>;\n\treverse?: boolean;\n};\n\nexport function visitParents<Tree extends import('unist').Node, Check extends Test>({\n\ttree,\n\ttest,\n\tenter: enterVisitor,\n\tleave: leaveVisitor,\n\treverse,\n}: Options<Tree, Check>) {\n\tif (!tree) {\n\t\tthrow new TypeError('A tree is required');\n\t}\n\n\tif (!enterVisitor && !leaveVisitor) {\n\t\tthrow new Error('At least one visitor (`enter` or `leave`) must be provided');\n\t}\n\n\tconst is = convert(test) as (\n\t\tnode: UnistNode,\n\t\tindex?: number,\n\t\tparent?: UnistParent\n\t) => node is Matches<InclusiveDescendant<Tree>, Check>;\n\tconst step = reverse ? -1 : 1;\n\n\tfactory(tree, undefined, [])();\n\n\tfunction factory(node: UnistNode, index: number | undefined, parents: UnistParent[]) {\n\t\tconst value = node as UnistNode & Record<string, unknown>;\n\n\t\tif (typeof value.type === 'string') {\n\t\t\tconst name =\n\t\t\t\t// `hast`\n\t\t\t\ttypeof value.tagName === 'string'\n\t\t\t\t\t? value.tagName\n\t\t\t\t\t: // `xast`\n\t\t\t\t\t\ttypeof value.name === 'string'\n\t\t\t\t\t\t? value.name\n\t\t\t\t\t\t: undefined;\n\n\t\t\tObject.defineProperty(visit, 'name', {\n\t\t\t\tvalue: 'node (' + node.type + (name ? '<' + name + '>' : '') + ')',\n\t\t\t});\n\t\t}\n\n\t\treturn visit;\n\n\t\tfunction visit() {\n\t\t\tlet result: Readonly<ActionTuple> = empty;\n\t\t\tlet subresult: Readonly<ActionTuple>;\n\t\t\tlet offset: number;\n\t\t\tlet grandparents: UnistParent[];\n\t\t\tconst isMatch = !test || is(node, index, parents[parents.length - 1]);\n\n\t\t\tif (isMatch) {\n\t\t\t\tresult = toResult(\n\t\t\t\t\tenterVisitor?.(\n\t\t\t\t\t\tnode as Matches<InclusiveDescendant<Tree>, Check>,\n\t\t\t\t\t\tparents as Array<Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>>\n\t\t\t\t\t)\n\t\t\t\t);\n\n\t\t\t\tif (result[0] === EXIT) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ('children' in node && node.children) {\n\t\t\t\tconst nodeAsParent = node as UnistParent;\n\n\t\t\t\tif (nodeAsParent.children && result[0] !== SKIP) {\n\t\t\t\t\toffset = (reverse ? nodeAsParent.children.length : -1) + step;\n\t\t\t\t\tgrandparents = parents.concat(nodeAsParent);\n\n\t\t\t\t\twhile (offset > -1 && offset < nodeAsParent.children.length) {\n\t\t\t\t\t\tconst child = nodeAsParent.children[offset];\n\n\t\t\t\t\t\tsubresult = factory(child, offset, grandparents)();\n\n\t\t\t\t\t\tif (subresult[0] === EXIT) {\n\t\t\t\t\t\t\treturn subresult;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\toffset = typeof subresult[1] === 'number' ? subresult[1] : offset + step;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (isMatch && leaveVisitor) {\n\t\t\t\tconst leaveResult = toResult(\n\t\t\t\t\tleaveVisitor(\n\t\t\t\t\t\tnode as Matches<InclusiveDescendant<Tree>, Check>,\n\t\t\t\t\t\tparents as Array<Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>>\n\t\t\t\t\t)\n\t\t\t\t);\n\n\t\t\t\treturn leaveResult === empty ? result : leaveResult;\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}\n\t}\n}\n\n/**\n * Turn a return value into a clean result.\n */\nfunction toResult(value: VisitorResult): Readonly<ActionTuple> {\n\tif (Array.isArray(value)) {\n\t\treturn value;\n\t}\n\n\tif (typeof value === 'number') {\n\t\treturn [CONTINUE, value];\n\t}\n\n\treturn value === null || value === undefined ? empty : [value];\n}\n\nexport type UnistNode = import('unist').Node;\nexport type UnistParent = import('unist').Parent;\n/**\n * Test from `unist-util-is`.\n *\n * Note: we have remove and add `undefined`, because otherwise when generating\n * automatic `.d.ts` files, TS tries to flatten paths from a local perspective,\n * which doesn’t work when publishing on npm.\n */\nexport type Test = Exclude<import('unist-util-is').Test, undefined> | undefined;\n/**\n * Get the value of a type guard `Fn`.\n */\nexport type Predicate<Fn, Fallback> = Fn extends (value: any) => value is infer Thing\n\t? Thing\n\t: Fallback;\n/**\n * Check whether a node matches a primitive check in the type system.\n */\nexport type MatchesOne<Value, Check> = Check extends null | undefined\n\t? Value\n\t: Value extends {\n\t\t\t\ttype: Check;\n\t\t }\n\t\t? Value\n\t\t: Value extends Check\n\t\t\t? Value\n\t\t\t: Check extends Function\n\t\t\t\t? Predicate<Check, Value> extends Value\n\t\t\t\t\t? Predicate<Check, Value>\n\t\t\t\t\t: never\n\t\t\t\t: never;\n/**\n * Check whether a node matches a check in the type system.\n */\nexport type Matches<Value, Check> =\n\tCheck extends Array<any> ? MatchesOne<Value, Check[keyof Check]> : MatchesOne<Value, Check>;\n/**\n * Number; capped reasonably.\n */\nexport type Uint = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10;\n/**\n * Increment a number in the type system.\n */\nexport type Increment<I extends Uint = 0> = I extends 0\n\t? 1\n\t: I extends 1\n\t\t? 2\n\t\t: I extends 2\n\t\t\t? 3\n\t\t\t: I extends 3\n\t\t\t\t? 4\n\t\t\t\t: I extends 4\n\t\t\t\t\t? 5\n\t\t\t\t\t: I extends 5\n\t\t\t\t\t\t? 6\n\t\t\t\t\t\t: I extends 6\n\t\t\t\t\t\t\t? 7\n\t\t\t\t\t\t\t: I extends 7\n\t\t\t\t\t\t\t\t? 8\n\t\t\t\t\t\t\t\t: I extends 8\n\t\t\t\t\t\t\t\t\t? 9\n\t\t\t\t\t\t\t\t\t: 10;\n/**\n * Collect nodes that can be parents of `Child`.\n */\nexport type InternalParent<\n\tNode extends import('unist').Node,\n\tChild extends import('unist').Node,\n> = Node extends import('unist').Parent\n\t? Node extends {\n\t\t\tchildren: (infer Children)[];\n\t\t}\n\t\t? Child extends Children\n\t\t\t? Node\n\t\t\t: never\n\t\t: never\n\t: never;\n/**\n * Collect nodes in `Tree` that can be parents of `Child`.\n */\nexport type Parent<\n\tTree extends import('unist').Node,\n\tChild extends import('unist').Node,\n> = InternalParent<InclusiveDescendant<Tree>, Child>;\n/**\n * Collect nodes in `Tree` that can be ancestors of `Child`.\n */\nexport type InternalAncestor<\n\tNode extends import('unist').Node,\n\tChild extends import('unist').Node,\n\tMax extends Uint = 10,\n\tDepth extends Uint = 0,\n> = Depth extends Max\n\t? never\n\t:\n\t\t\t| InternalParent<Node, Child>\n\t\t\t| InternalAncestor<Node, InternalParent<Node, Child>, Max, Increment<Depth>>;\n/**\n * Collect nodes in `Tree` that can be ancestors of `Child`.\n */\nexport type Ancestor<\n\tTree extends import('unist').Node,\n\tChild extends import('unist').Node,\n> = InternalAncestor<InclusiveDescendant<Tree>, Child>;\n/**\n * Collect all (inclusive) descendants of `Tree`.\n *\n * > 👉 **Note**: for performance reasons, this seems to be the fastest way to\n * > recurse without actually running into an infinite loop, which the\n * > previous version did.\n * >\n * > Practically, a max of `2` is typically enough assuming a `Root` is\n * > passed, but it doesn’t improve performance.\n * > It gets higher with `List > ListItem > Table > TableRow > TableCell`.\n * > Using up to `10` doesn’t hurt or help either.\n */\nexport type InclusiveDescendant<\n\tTree extends import('unist').Node,\n\tMax extends Uint = 10,\n\tDepth extends Uint = 0,\n> = Tree extends UnistParent\n\t? Depth extends Max\n\t\t? Tree\n\t\t: Tree | InclusiveDescendant<Tree['children'][number], Max, Increment<Depth>>\n\t: Tree;\n/**\n * Union of the action types.\n */\nexport type Action = 'skip' | boolean;\n/**\n * Move to the sibling at `index` next (after node itself is completely\n * traversed).\n *\n * Useful if mutating the tree, such as removing the node the visitor is\n * currently on, or any of its previous siblings.\n * Results less than 0 or greater than or equal to `children.length` stop\n * traversing the parent.\n */\nexport type Index = number;\n/**\n * List with one or two values, the first an action, the second an index.\n */\nexport type ActionTuple = [(Action | null | undefined | void)?, (Index | null | undefined)?];\n/**\n * Any value that can be returned from a visitor.\n */\nexport type VisitorResult =\n\t| Action\n\t| [(void | Action | null | undefined)?, (number | null | undefined)?]\n\t| Index\n\t| null\n\t| undefined\n\t| void;\n/**\n * Handle a node (matching `test`, if given).\n *\n * Visitors are free to transform `node`.\n * They can also transform the parent of node (the last of `ancestors`).\n *\n * Replacing `node` itself, if `SKIP` is not returned, still causes its\n * descendants to be walked (which is a bug).\n *\n * When adding or removing previous siblings of `node` (or next siblings, in\n * case of reverse), the `Visitor` should return a new `Index` to specify the\n * sibling to traverse after `node` is traversed.\n * Adding or removing next siblings of `node` (or previous siblings, in case\n * of reverse) is handled as expected without needing to return a new `Index`.\n *\n * Removing the children property of an ancestor still results in them being\n * traversed.\n */\nexport type Visitor<\n\tVisited extends import('unist').Node = import('unist').Node,\n\tVisitedParents extends import('unist').Parent = import('unist').Parent,\n> = (node: Visited, ancestors: Array<VisitedParents>) => VisitorResult;\n\n/**\n * Build a typed `Visitor` function from a tree and a test.\n *\n * It will infer which values are passed as `node` and which as `parents`.\n */\nexport type BuildVisitor<\n\tTree extends import('unist').Node = import('unist').Node,\n\tCheck extends Test = Test,\n> = Visitor<\n\tMatches<InclusiveDescendant<Tree>, Check>,\n\tAncestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>\n>;\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/unist/visit.ts"],"names":["empty","CONTINUE","EXIT","SKIP","visitParents","tree","test","enterVisitor","leaveVisitor","reverse","is","convert","step","factory","node","index","parents","value","name","visit","result","subresult","offset","grandparents","isMatch","toResult","nodeAsParent","child","leaveResult"],"mappings":"oCAEA,MAAMA,CAAqB,CAAA,EAKdC,CAAAA,CAAAA,CAAW,CAKXC,CAAAA,CAAAA,CAAAA,CAAO,CAKPC,CAAAA,CAAAA,CAAAA,CAAO,OAUb,SAASC,CAAoE,CAAA,CACnF,IAAAC,CAAAA,CAAAA,CACA,IAAAC,CAAAA,CAAAA,CACA,KAAOC,CAAAA,CAAAA,CACP,KAAOC,CAAAA,CAAAA,CACP,OAAAC,CAAAA,CACD,CAAyB,CAAA,CACxB,GAAI,CAACJ,CAAAA,CACJ,MAAM,IAAI,SAAU,CAAA,oBAAoB,CAGzC,CAAA,GAAI,CAACE,CAAAA,EAAgB,CAACC,CAAAA,CACrB,MAAM,IAAI,KAAM,CAAA,4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Tuple = [];\n\n/**\n * Continue traversing as normal.\n */\nexport const CONTINUE = true;\n\n/**\n * Stop traversing immediately.\n */\nexport const EXIT = false;\n\n/**\n * Do not traverse this node’s children.\n */\nexport const SKIP = 'skip';\n\nexport type Options<Tree extends import('unist').Node, Check extends Test> = {\n\ttree: Tree;\n\ttest?: Check;\n\tenter?: BuildVisitor<Tree, Check>;\n\tleave?: BuildVisitor<Tree, Check>;\n\treverse?: boolean;\n};\n\nexport function visitParents<Tree extends import('unist').Node, Check extends Test>({\n\ttree,\n\ttest,\n\tenter: enterVisitor,\n\tleave: leaveVisitor,\n\treverse,\n}: Options<Tree, Check>) {\n\tif (!tree) {\n\t\tthrow new TypeError('A tree is required');\n\t}\n\n\tif (!enterVisitor && !leaveVisitor) {\n\t\tthrow new Error('At least one visitor (`enter` or `leave`) must be provided');\n\t}\n\n\tconst is = convert(test) as (\n\t\tnode: UnistNode,\n\t\tindex?: number,\n\t\tparent?: UnistParent\n\t) => node is Matches<InclusiveDescendant<Tree>, Check>;\n\tconst step = reverse ? -1 : 1;\n\n\tfactory(tree, undefined, [])();\n\n\tfunction factory(node: UnistNode, index: number | undefined, parents: UnistParent[]) {\n\t\tconst value = node as UnistNode & Record<string, unknown>;\n\n\t\tif (typeof value.type === 'string') {\n\t\t\tconst name =\n\t\t\t\t// `hast`\n\t\t\t\ttypeof value.tagName === 'string'\n\t\t\t\t\t? value.tagName\n\t\t\t\t\t: // `xast`\n\t\t\t\t\t\ttypeof value.name === 'string'\n\t\t\t\t\t\t? value.name\n\t\t\t\t\t\t: undefined;\n\n\t\t\tObject.defineProperty(visit, 'name', {\n\t\t\t\tvalue: 'node (' + node.type + (name ? '<' + name + '>' : '') + ')',\n\t\t\t});\n\t\t}\n\n\t\treturn visit;\n\n\t\tfunction visit() {\n\t\t\tlet result: Readonly<ActionTuple> = empty;\n\t\t\tlet subresult: Readonly<ActionTuple>;\n\t\t\tlet offset: number;\n\t\t\tlet grandparents: UnistParent[];\n\t\t\tconst isMatch = !test || is(node, index, parents[parents.length - 1]);\n\n\t\t\tif (isMatch) {\n\t\t\t\tresult = toResult(\n\t\t\t\t\tenterVisitor?.(\n\t\t\t\t\t\tnode as Matches<InclusiveDescendant<Tree>, Check>,\n\t\t\t\t\t\tparents as Array<Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>>\n\t\t\t\t\t)\n\t\t\t\t);\n\n\t\t\t\tif (result[0] === EXIT) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ('children' in node && node.children) {\n\t\t\t\tconst nodeAsParent = node as UnistParent;\n\n\t\t\t\tif (nodeAsParent.children && result[0] !== SKIP) {\n\t\t\t\t\toffset = (reverse ? nodeAsParent.children.length : -1) + step;\n\t\t\t\t\tgrandparents = parents.concat(nodeAsParent);\n\n\t\t\t\t\twhile (offset > -1 && offset < nodeAsParent.children.length) {\n\t\t\t\t\t\tconst child = nodeAsParent.children[offset];\n\n\t\t\t\t\t\tsubresult = factory(child, offset, grandparents)();\n\n\t\t\t\t\t\tif (subresult[0] === EXIT) {\n\t\t\t\t\t\t\treturn subresult;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\toffset = typeof subresult[1] === 'number' ? subresult[1] : offset + step;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (isMatch && leaveVisitor) {\n\t\t\t\tconst leaveResult = toResult(\n\t\t\t\t\tleaveVisitor(\n\t\t\t\t\t\tnode as Matches<InclusiveDescendant<Tree>, Check>,\n\t\t\t\t\t\tparents as Array<Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>>\n\t\t\t\t\t)\n\t\t\t\t);\n\n\t\t\t\treturn leaveResult === empty ? result : leaveResult;\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}\n\t}\n}\n\n/**\n * Turn a return value into a clean result.\n */\nfunction toResult(value: VisitorResult): Readonly<ActionTuple> {\n\tif (Array.isArray(value)) {\n\t\treturn value;\n\t}\n\n\tif (typeof value === 'number') {\n\t\treturn [CONTINUE, value];\n\t}\n\n\treturn value === null || value === undefined ? empty : [value];\n}\n\nexport type UnistNode = import('unist').Node;\nexport type UnistParent = import('unist').Parent;\n/**\n * Test from `unist-util-is`.\n *\n * Note: we have remove and add `undefined`, because otherwise when generating\n * automatic `.d.ts` files, TS tries to flatten paths from a local perspective,\n * which doesn’t work when publishing on npm.\n */\nexport type Test = Exclude<import('unist-util-is').Test, undefined> | undefined;\n/**\n * Get the value of a type guard `Fn`.\n */\nexport type Predicate<Fn, Fallback> = Fn extends (value: any) => value is infer Thing\n\t? Thing\n\t: Fallback;\n/**\n * Check whether a node matches a primitive check in the type system.\n */\nexport type MatchesOne<Value, Check> = Check extends null | undefined\n\t? Value\n\t: Value extends {\n\t\t\t\ttype: Check;\n\t\t }\n\t\t? Value\n\t\t: Value extends Check\n\t\t\t? Value\n\t\t\t: Check extends Function\n\t\t\t\t? Predicate<Check, Value> extends Value\n\t\t\t\t\t? Predicate<Check, Value>\n\t\t\t\t\t: never\n\t\t\t\t: never;\n/**\n * Check whether a node matches a check in the type system.\n */\nexport type Matches<Value, Check> =\n\tCheck extends Array<any> ? MatchesOne<Value, Check[keyof Check]> : MatchesOne<Value, Check>;\n/**\n * Number; capped reasonably.\n */\nexport type Uint = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10;\n/**\n * Increment a number in the type system.\n */\nexport type Increment<I extends Uint = 0> = I extends 0\n\t? 1\n\t: I extends 1\n\t\t? 2\n\t\t: I extends 2\n\t\t\t? 3\n\t\t\t: I extends 3\n\t\t\t\t? 4\n\t\t\t\t: I extends 4\n\t\t\t\t\t? 5\n\t\t\t\t\t: I extends 5\n\t\t\t\t\t\t? 6\n\t\t\t\t\t\t: I extends 6\n\t\t\t\t\t\t\t? 7\n\t\t\t\t\t\t\t: I extends 7\n\t\t\t\t\t\t\t\t? 8\n\t\t\t\t\t\t\t\t: I extends 8\n\t\t\t\t\t\t\t\t\t? 9\n\t\t\t\t\t\t\t\t\t: 10;\n/**\n * Collect nodes that can be parents of `Child`.\n */\nexport type InternalParent<\n\tNode extends import('unist').Node,\n\tChild extends import('unist').Node,\n> = Node extends import('unist').Parent\n\t? Node extends {\n\t\t\tchildren: (infer Children)[];\n\t\t}\n\t\t? Child extends Children\n\t\t\t? Node\n\t\t\t: never\n\t\t: never\n\t: never;\n/**\n * Collect nodes in `Tree` that can be parents of `Child`.\n */\nexport type Parent<\n\tTree extends import('unist').Node,\n\tChild extends import('unist').Node,\n> = InternalParent<InclusiveDescendant<Tree>, Child>;\n/**\n * Collect nodes in `Tree` that can be ancestors of `Child`.\n */\nexport type InternalAncestor<\n\tNode extends import('unist').Node,\n\tChild extends import('unist').Node,\n\tMax extends Uint = 10,\n\tDepth extends Uint = 0,\n> = Depth extends Max\n\t? never\n\t:\n\t\t\t| InternalParent<Node, Child>\n\t\t\t| InternalAncestor<Node, InternalParent<Node, Child>, Max, Increment<Depth>>;\n/**\n * Collect nodes in `Tree` that can be ancestors of `Child`.\n */\nexport type Ancestor<\n\tTree extends import('unist').Node,\n\tChild extends import('unist').Node,\n> = InternalAncestor<InclusiveDescendant<Tree>, Child>;\n/**\n * Collect all (inclusive) descendants of `Tree`.\n *\n * > 👉 **Note**: for performance reasons, this seems to be the fastest way to\n * > recurse without actually running into an infinite loop, which the\n * > previous version did.\n * >\n * > Practically, a max of `2` is typically enough assuming a `Root` is\n * > passed, but it doesn’t improve performance.\n * > It gets higher with `List > ListItem > Table > TableRow > TableCell`.\n * > Using up to `10` doesn’t hurt or help either.\n */\nexport type InclusiveDescendant<\n\tTree extends import('unist').Node,\n\tMax extends Uint = 10,\n\tDepth extends Uint = 0,\n> = Tree extends UnistParent\n\t? Depth extends Max\n\t\t? Tree\n\t\t: Tree | InclusiveDescendant<Tree['children'][number], Max, Increment<Depth>>\n\t: Tree;\n/**\n * Union of the action types.\n */\nexport type Action = 'skip' | boolean;\n/**\n * Move to the sibling at `index` next (after node itself is completely\n * traversed).\n *\n * Useful if mutating the tree, such as removing the node the visitor is\n * currently on, or any of its previous siblings.\n * Results less than 0 or greater than or equal to `children.length` stop\n * traversing the parent.\n */\nexport type Index = number;\n/**\n * List with one or two values, the first an action, the second an index.\n */\nexport type ActionTuple = [(Action | null | undefined | void)?, (Index | null | undefined)?];\n/**\n * Any value that can be returned from a visitor.\n */\nexport type VisitorResult =\n\t| Action\n\t| [(void | Action | null | undefined)?, (number | null | undefined)?]\n\t| Index\n\t| null\n\t| undefined\n\t| void;\n/**\n * Handle a node (matching `test`, if given).\n *\n * Visitors are free to transform `node`.\n * They can also transform the parent of node (the last of `ancestors`).\n *\n * Replacing `node` itself, if `SKIP` is not returned, still causes its\n * descendants to be walked (which is a bug).\n *\n * When adding or removing previous siblings of `node` (or next siblings, in\n * case of reverse), the `Visitor` should return a new `Index` to specify the\n * sibling to traverse after `node` is traversed.\n * Adding or removing next siblings of `node` (or previous siblings, in case\n * of reverse) is handled as expected without needing to return a new `Index`.\n *\n * Removing the children property of an ancestor still results in them being\n * traversed.\n */\nexport type Visitor<\n\tVisited extends import('unist').Node = import('unist').Node,\n\tVisitedParents extends import('unist').Parent = import('unist').Parent,\n> = (node: Visited, ancestors: Array<VisitedParents>) => VisitorResult;\n\n/**\n * Build a typed `Visitor` function from a tree and a test.\n *\n * It will infer which values are passed as `node` and which as `parents`.\n */\nexport type BuildVisitor<\n\tTree extends import('unist').Node = import('unist').Node,\n\tCheck extends Test = Test,\n> = Visitor<\n\tMatches<InclusiveDescendant<Tree>, Check>,\n\tAncestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>\n>;\n"]}
|
package/dist/values.d.ts
CHANGED
|
@@ -35,5 +35,39 @@ type MaybeAsyncThunk<T> = MaybeThunk<MaybePromise<T>>;
|
|
|
35
35
|
* @see MaybeThunk
|
|
36
36
|
*/
|
|
37
37
|
declare function loadThunkValue<T>(value: MaybeThunk<T>): T;
|
|
38
|
+
type NextDepth = [1, 2, 3, 4, 5, 6, 7];
|
|
39
|
+
/**
|
|
40
|
+
* Extract key-value entry pairs for each node in an object tree.
|
|
41
|
+
*/
|
|
42
|
+
type NodeEntries<T, NoCircle = never, MaxDepth extends number = 0> = MaxDepth extends 7 ? never : T extends object ? {
|
|
43
|
+
[Key in keyof T & string]-?: T[Key] extends NoCircle ? never : NodeEntries<T[Key], NoCircle | T[Key], NextDepth[MaxDepth]> extends infer Nested ? Nested extends {
|
|
44
|
+
key: string;
|
|
45
|
+
value: unknown;
|
|
46
|
+
} ? Nested['key'] extends '' ? {
|
|
47
|
+
key: Key;
|
|
48
|
+
value: Nested['value'];
|
|
49
|
+
} : {
|
|
50
|
+
key: Key;
|
|
51
|
+
value: T[Key];
|
|
52
|
+
} | {
|
|
53
|
+
key: `${Key}.${Nested['key']}`;
|
|
54
|
+
value: Nested['value'];
|
|
55
|
+
} : never : never;
|
|
56
|
+
}[keyof T & string] : {
|
|
57
|
+
key: '';
|
|
58
|
+
value: T;
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* Sets a value nested in an object tree, creating the path as needed.
|
|
62
|
+
*/
|
|
63
|
+
declare function setNested<T extends object, const P extends NodeEntries<T>['key']>(obj: T, prop: P, value: Extract<NodeEntries<T>, {
|
|
64
|
+
key: P;
|
|
65
|
+
}>['value']): void;
|
|
66
|
+
/**
|
|
67
|
+
* Sets a value nested in an object tree, creating the path as needed, if it is not already set to a non-nullish value.
|
|
68
|
+
*/
|
|
69
|
+
declare function setNestedIfNullish<T extends object, const P extends NodeEntries<T>['key']>(obj: T, prop: P, value: Extract<NodeEntries<T>, {
|
|
70
|
+
key: P;
|
|
71
|
+
}>['value']): void;
|
|
38
72
|
|
|
39
|
-
export { type MaybeAsyncThunk, type MaybePromise, type MaybeThunk, loadThunkValue };
|
|
73
|
+
export { type MaybeAsyncThunk, type MaybePromise, type MaybeThunk, type NodeEntries, loadThunkValue, setNested, setNestedIfNullish };
|
package/dist/values.js
CHANGED
|
@@ -1,5 +1,2 @@
|
|
|
1
|
-
function
|
|
2
|
-
|
|
3
|
-
export { T as loadThunkValue };
|
|
4
|
-
//# sourceMappingURL=values.js.map
|
|
1
|
+
function p(n){return typeof n=="function"?n():n}function u(n,i,y){if(n==null)throw new Error("Root object is nullish.");const t=i.split(".");let e=n;for(const[l,s]of t.slice(0,-1).entries()){const o=e[s],r=t.slice(0,l).join(".");if(o==null){e=e[s]={};continue}if(typeof o!="object")throw new Error(`Cannot set property on ${typeof o} value at "${r}".`);e=o;}e[t[t.length-1]]=y;}function a(n,i,y){if(n==null)throw new Error("Root object is nullish.");const t=i.split(".");let e=n;for(const[s,o]of t.slice(0,-1).entries()){const r=e[o],c=t.slice(0,s).join(".");if(r==null){e=e[o]={};continue}if(typeof r!="object")throw new Error(`Cannot set property on ${typeof r} value at "${c}".`);e=r;}const l=t[t.length-1];e[l]==null&&(e[t[t.length-1]]=y);}export{p as loadThunkValue,u as setNested,a as setNestedIfNullish};//# sourceMappingURL=values.js.map
|
|
5
2
|
//# sourceMappingURL=values.js.map
|
package/dist/values.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/values.ts"],"names":["loadThunkValue","value"],"mappings":"AAuCO,SAASA,CAAAA,CAAkBC,EAAyB,CAC1D,OAAO,OAAOA,CAAU,EAAA,UAAA,CAAaA,CAAM,EAAA,
|
|
1
|
+
{"version":3,"sources":["../src/values.ts"],"names":["loadThunkValue","value","setNested","obj","prop","parts","current","idx","propName","next","path","setNestedIfNullish","key"],"mappings":"AAuCO,SAASA,CAAAA,CAAkBC,EAAyB,CAC1D,OAAO,OAAOA,CAAU,EAAA,UAAA,CAAaA,GAAUA,CAAAA,CAChD,CAkCO,SAASC,CAAAA,CACfC,EACAC,CACAH,CAAAA,CAAAA,CACO,CACP,GAAIE,CAAAA,EAAO,IAAM,CAAA,MAAM,IAAI,KAAA,CAAM,yBAAyB,CAC1D,CAAA,MAAME,EAAQD,CAAK,CAAA,KAAA,CAAM,GAAG,CAE5B,CAAA,IAAIE,EAAeH,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,IAAI,KAAM,CAAA,CAAA,uBAAA,EAA0B,OAAOA,CAAI,CAAcC,WAAAA,EAAAA,CAAI,IAAI,CAE5EJ,CAAAA,CAAAA,CAAUG,EACX,CAEA,MAAMG,EAAMP,CAAMA,CAAAA,CAAAA,CAAM,OAAS,CAAC,CAAA,CAC9BC,EAAQM,CAAG,CAAA,EAAK,OACnBN,CAAQD,CAAAA,CAAAA,CAAMA,EAAM,MAAS,CAAA,CAAC,CAAC,CAAA,CAAIJ,CAErC,EAAA","file":"values.js","sourcesContent":["/**\n * A value that can be might be pending to be resolved.\n */\nexport type MaybePromise<T> = T | Promise<T>;\n\n/**\n * A value or a thunk for a value.\n *\n * A \"thunk\" is a function that takes no arguments and return\n * a value that is potentially expensive to compute.\n * This can be used when the value might not be needed and as\n * such can be computed on demand potentially saving the\n * expensive computation.\n *\n * If the value is not expensive to compute it can be used directly\n * for simplicity.\n *\n * A value type that is itself a function cannot be a \"maybe\" thunk.\n *\n * @see https://en.wikipedia.org/wiki/Thunk\n */\nexport type MaybeThunk<T> = T extends Function ? never : T | (() => T);\n\n/**\n * A value or a thunk for a synchronous or asynchronous value.\n *\n * @see MaybePromise\n * @see MaybeThunk\n */\nexport type MaybeAsyncThunk<T> = MaybeThunk<MaybePromise<T>>;\n\n/**\n * Load a value from a possibly thunk argument.\n *\n * If the value is a thunk it is called and the result is returned.\n * Otherwise the value itself is returned.\n *\n * @see MaybeThunk\n */\nexport function loadThunkValue<T>(value: MaybeThunk<T>): T {\n\treturn typeof value === 'function' ? value() : value;\n}\n\ntype NextDepth = [1, 2, 3, 4, 5, 6, 7];\n\n/**\n * Extract key-value entry pairs for each node in an object tree.\n */\nexport type NodeEntries<T, NoCircle = never, MaxDepth extends number = 0> = MaxDepth extends 7\n\t? never\n\t: T extends object\n\t\t? {\n\t\t\t\t[Key in keyof T & string]-?: T[Key] extends NoCircle\n\t\t\t\t\t? never\n\t\t\t\t\t: NodeEntries<T[Key], NoCircle | T[Key], NextDepth[MaxDepth]> extends infer Nested\n\t\t\t\t\t\t? Nested extends { key: string; value: unknown }\n\t\t\t\t\t\t\t? Nested['key'] extends ''\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\tkey: Key;\n\t\t\t\t\t\t\t\t\t\tvalue: Nested['value'];\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t:\n\t\t\t\t\t\t\t\t\t\t| { key: Key; value: T[Key] }\n\t\t\t\t\t\t\t\t\t\t| {\n\t\t\t\t\t\t\t\t\t\t\t\tkey: `${Key}.${Nested['key']}`;\n\t\t\t\t\t\t\t\t\t\t\t\tvalue: Nested['value'];\n\t\t\t\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t: never\n\t\t\t\t\t\t: never;\n\t\t\t}[keyof T & string]\n\t\t: { key: ''; value: T };\n\n/**\n * Sets a value nested in an object tree, creating the path as needed.\n */\nexport function setNested<T extends object, const P extends NodeEntries<T>['key']>(\n\tobj: T,\n\tprop: P,\n\tvalue: Extract<NodeEntries<T>, { key: P }>['value']\n): void {\n\tif (obj == null) throw new Error('Root object is nullish.');\n\tconst parts = prop.split('.');\n\n\tlet current: any = obj;\n\tfor (const [idx, propName] of parts.slice(0, -1).entries()) {\n\t\tconst next = current[propName];\n\t\tconst path = parts.slice(0, idx).join('.');\n\n\t\tif (next == null) {\n\t\t\tcurrent = current[propName] = {};\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (typeof next !== 'object')\n\t\t\tthrow new Error(`Cannot set property on ${typeof next} value at \"${path}\".`);\n\n\t\tcurrent = next;\n\t}\n\n\tcurrent[parts[parts.length - 1]] = value;\n}\n\n/**\n * Sets a value nested in an object tree, creating the path as needed, if it is not already set to a non-nullish value.\n */\nexport function setNestedIfNullish<T extends object, const P extends NodeEntries<T>['key']>(\n\tobj: T,\n\tprop: P,\n\tvalue: Extract<NodeEntries<T>, { key: P }>['value']\n): void {\n\tif (obj == null) throw new Error('Root object is nullish.');\n\tconst parts = prop.split('.');\n\n\tlet current: any = obj;\n\tfor (const [idx, propName] of parts.slice(0, -1).entries()) {\n\t\tconst next = current[propName];\n\t\tconst path = parts.slice(0, idx).join('.');\n\n\t\tif (next == null) {\n\t\t\tcurrent = current[propName] = {};\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (typeof next !== 'object')\n\t\t\tthrow new Error(`Cannot set property on ${typeof next} value at \"${path}\".`);\n\n\t\tcurrent = next;\n\t}\n\n\tconst key = parts[parts.length - 1];\n\tif (current[key] == null) {\n\t\tcurrent[parts[parts.length - 1]] = value;\n\t}\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inox-tools/utils",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0-beta.0",
|
|
4
4
|
"description": "A collection of utilities used throughout Inox Tools",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"utilities"
|
|
@@ -22,19 +22,19 @@
|
|
|
22
22
|
"devDependencies": {
|
|
23
23
|
"@types/hast": "^3.0.4",
|
|
24
24
|
"@types/mdast": "^4.0.4",
|
|
25
|
-
"@types/node": "^22.
|
|
25
|
+
"@types/node": "^22.8.4",
|
|
26
26
|
"@types/unist": "^3.0.3",
|
|
27
27
|
"@types/xast": "^2.0.4",
|
|
28
|
-
"@vitest/coverage-v8": "^2.1.
|
|
29
|
-
"@vitest/ui": "^2.1.
|
|
30
|
-
"astro": "^
|
|
28
|
+
"@vitest/coverage-v8": "^2.1.4",
|
|
29
|
+
"@vitest/ui": "^2.1.4",
|
|
30
|
+
"astro": "^5.0.0-beta",
|
|
31
31
|
"jest-extended": "^4.0.2",
|
|
32
|
-
"mdast-util-from-markdown": "^2.0.
|
|
33
|
-
"tsup": "8.
|
|
34
|
-
"typescript": "^5.
|
|
32
|
+
"mdast-util-from-markdown": "^2.0.2",
|
|
33
|
+
"tsup": "8.3.5",
|
|
34
|
+
"typescript": "^5.6.3",
|
|
35
35
|
"unist-util-is": "^6.0.0",
|
|
36
|
-
"vite": "^
|
|
37
|
-
"vitest": "^2.1.
|
|
36
|
+
"vite": "^6.0.0-beta",
|
|
37
|
+
"vitest": "^2.1.4"
|
|
38
38
|
},
|
|
39
39
|
"scripts": {
|
|
40
40
|
"build": "tsup",
|
package/src/values.ts
CHANGED
|
@@ -40,3 +40,95 @@ export type MaybeAsyncThunk<T> = MaybeThunk<MaybePromise<T>>;
|
|
|
40
40
|
export function loadThunkValue<T>(value: MaybeThunk<T>): T {
|
|
41
41
|
return typeof value === 'function' ? value() : value;
|
|
42
42
|
}
|
|
43
|
+
|
|
44
|
+
type NextDepth = [1, 2, 3, 4, 5, 6, 7];
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Extract key-value entry pairs for each node in an object tree.
|
|
48
|
+
*/
|
|
49
|
+
export type NodeEntries<T, NoCircle = never, MaxDepth extends number = 0> = MaxDepth extends 7
|
|
50
|
+
? never
|
|
51
|
+
: T extends object
|
|
52
|
+
? {
|
|
53
|
+
[Key in keyof T & string]-?: T[Key] extends NoCircle
|
|
54
|
+
? never
|
|
55
|
+
: NodeEntries<T[Key], NoCircle | T[Key], NextDepth[MaxDepth]> extends infer Nested
|
|
56
|
+
? Nested extends { key: string; value: unknown }
|
|
57
|
+
? Nested['key'] extends ''
|
|
58
|
+
? {
|
|
59
|
+
key: Key;
|
|
60
|
+
value: Nested['value'];
|
|
61
|
+
}
|
|
62
|
+
:
|
|
63
|
+
| { key: Key; value: T[Key] }
|
|
64
|
+
| {
|
|
65
|
+
key: `${Key}.${Nested['key']}`;
|
|
66
|
+
value: Nested['value'];
|
|
67
|
+
}
|
|
68
|
+
: never
|
|
69
|
+
: never;
|
|
70
|
+
}[keyof T & string]
|
|
71
|
+
: { key: ''; value: T };
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Sets a value nested in an object tree, creating the path as needed.
|
|
75
|
+
*/
|
|
76
|
+
export function setNested<T extends object, const P extends NodeEntries<T>['key']>(
|
|
77
|
+
obj: T,
|
|
78
|
+
prop: P,
|
|
79
|
+
value: Extract<NodeEntries<T>, { key: P }>['value']
|
|
80
|
+
): void {
|
|
81
|
+
if (obj == null) throw new Error('Root object is nullish.');
|
|
82
|
+
const parts = prop.split('.');
|
|
83
|
+
|
|
84
|
+
let current: any = obj;
|
|
85
|
+
for (const [idx, propName] of parts.slice(0, -1).entries()) {
|
|
86
|
+
const next = current[propName];
|
|
87
|
+
const path = parts.slice(0, idx).join('.');
|
|
88
|
+
|
|
89
|
+
if (next == null) {
|
|
90
|
+
current = current[propName] = {};
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (typeof next !== 'object')
|
|
95
|
+
throw new Error(`Cannot set property on ${typeof next} value at "${path}".`);
|
|
96
|
+
|
|
97
|
+
current = next;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
current[parts[parts.length - 1]] = value;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Sets a value nested in an object tree, creating the path as needed, if it is not already set to a non-nullish value.
|
|
105
|
+
*/
|
|
106
|
+
export function setNestedIfNullish<T extends object, const P extends NodeEntries<T>['key']>(
|
|
107
|
+
obj: T,
|
|
108
|
+
prop: P,
|
|
109
|
+
value: Extract<NodeEntries<T>, { key: P }>['value']
|
|
110
|
+
): void {
|
|
111
|
+
if (obj == null) throw new Error('Root object is nullish.');
|
|
112
|
+
const parts = prop.split('.');
|
|
113
|
+
|
|
114
|
+
let current: any = obj;
|
|
115
|
+
for (const [idx, propName] of parts.slice(0, -1).entries()) {
|
|
116
|
+
const next = current[propName];
|
|
117
|
+
const path = parts.slice(0, idx).join('.');
|
|
118
|
+
|
|
119
|
+
if (next == null) {
|
|
120
|
+
current = current[propName] = {};
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (typeof next !== 'object')
|
|
125
|
+
throw new Error(`Cannot set property on ${typeof next} value at "${path}".`);
|
|
126
|
+
|
|
127
|
+
current = next;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const key = parts[parts.length - 1];
|
|
131
|
+
if (current[key] == null) {
|
|
132
|
+
current[parts[parts.length - 1]] = value;
|
|
133
|
+
}
|
|
134
|
+
}
|