@d-matrix/utils 1.23.0 → 1.24.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.
@@ -14,3 +14,12 @@ export declare const nodeCountAtDepth: <T extends Record<string, any>>(root: T,
14
14
  * @returns 找到的节点
15
15
  */
16
16
  export declare const findNode: <T extends Record<string, any>>(tree: T[], predicate: (node: T) => boolean, childrenKey?: string) => T | null;
17
+ /**
18
+ * 根据子节点查找父节点
19
+ * @param tree
20
+ * @param child 子节点
21
+ * @param indentityKey 节点唯一id字段名称
22
+ * @param childrenKey 节点的子节点的字段名称
23
+ * @returns
24
+ */
25
+ export declare const findParent: <T extends Record<string, any>>(tree: T | undefined, child: T | undefined, indentityKey?: string, childrenKey?: string) => T | null;
@@ -41,3 +41,30 @@ export const findNode = (tree, predicate, childrenKey = 'children') => {
41
41
  }
42
42
  return null;
43
43
  };
44
+ /**
45
+ * 根据子节点查找父节点
46
+ * @param tree
47
+ * @param child 子节点
48
+ * @param indentityKey 节点唯一id字段名称
49
+ * @param childrenKey 节点的子节点的字段名称
50
+ * @returns
51
+ */
52
+ export const findParent = (tree, child, indentityKey = 'id', childrenKey = 'children') => {
53
+ if (tree === undefined || child === undefined) {
54
+ return null;
55
+ }
56
+ const children = tree[childrenKey];
57
+ if (Array.isArray(children)) {
58
+ const count = children.length;
59
+ for (let i = 0; i < count; i++) {
60
+ if (children[i][indentityKey] === child[indentityKey]) {
61
+ return tree;
62
+ }
63
+ const parent = findParent(children[i], child, indentityKey, childrenKey);
64
+ if (parent !== null) {
65
+ return parent;
66
+ }
67
+ }
68
+ }
69
+ return null;
70
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@d-matrix/utils",
3
3
  "sideEffects": false,
4
- "version": "1.23.0",
4
+ "version": "1.24.0",
5
5
  "description": "A dozen of utils for Front-End Development",
6
6
  "main": "dist/index.js",
7
7
  "scripts": {
package/readme.md CHANGED
@@ -390,6 +390,23 @@ const actual2 = tree.findNode([root], (node) => node.id === 33);
390
390
  expect(actual2).to.be.deep.equal(root.children[1].children[2]);
391
391
  ```
392
392
 
393
+ - `tree.findNode(tree, child, indentityKey, childrenKey)`
394
+
395
+ 根据子节点查找父节点
396
+
397
+ ```ts
398
+ const treeData = {
399
+ code: 1,
400
+ subs: [
401
+ { code: 2, subs: [{ code: 21 }, { code: 22 }, { code: 23 }] },
402
+ { code: 3, subs: [{ code: 31 }, { code: 32 }, { code: 33 }] },
403
+ ],
404
+ };
405
+
406
+ const actual = tree.findParent(treeData, treeData.subs[1].subs[2], 'code', 'subs');
407
+ expect(actual).to.be.deep.equal(treeData.subs[1]);
408
+ ```
409
+
393
410
  ### file
394
411
 
395
412
  - `toImage(file: BlobPart | FileURL, options?: BlobPropertyBag): Promise<HTMLImageElement>`