Skip to content

Commit 6ef94e1

Browse files
committed
Add memoized insert method
1 parent 1c6b119 commit 6ef94e1

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

src/utils/memoized-tree-data-utils.js

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { insertNode } from './tree-data-utils';
2+
3+
let memoizedInsertArgsArray = [];
4+
let memoizedInsertKeysArray = [];
5+
let memoizedInsertResult = null;
6+
7+
/**
8+
* Insert a node into the tree at the given depth, after the minimum index
9+
*
10+
* @param {!Object[]} treeData - Tree data
11+
* @param {!number} depth - The depth to insert the node at (the first level of the array being depth 0)
12+
* @param {!number} minimumTreeIndex - The lowest possible treeIndex to insert the node at
13+
* @param {!Object} newNode - The node to insert into the tree
14+
* @param {boolean=} ignoreCollapsed - Ignore children of nodes without `expanded` set to `true`
15+
* @param {boolean=} expandParent - If true, expands the parent of the inserted node
16+
* @param {!function} getNodeKey - Function to get the key from the nodeData and tree index
17+
*
18+
* @return {Object} result
19+
* @return {Object[]} result.treeData - The tree data with the node added
20+
* @return {number} result.treeIndex - The tree index at which the node was inserted
21+
* @return {number[]|string[]} result.path - Array of keys leading to the node location after insertion
22+
*/
23+
export function memoizedInsertNode(args) {
24+
const keysArray = Object.keys(args).sort();
25+
const argsArray = keysArray.map(key => args[key]);
26+
27+
// If the arguments for the last insert operation are different than this time,
28+
// recalculate the result
29+
if (argsArray.length !== memoizedInsertArgsArray.length ||
30+
argsArray.some((arg, index) => arg !== memoizedInsertArgsArray[index]) ||
31+
keysArray.some((key, index) => key !== memoizedInsertKeysArray[index])
32+
) {
33+
memoizedInsertArgsArray = argsArray;
34+
memoizedInsertKeysArray = keysArray;
35+
memoizedInsertResult = insertNode(args);
36+
}
37+
38+
return memoizedInsertResult;
39+
}
+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import {
2+
insertNode,
3+
} from './tree-data-utils';
4+
5+
import {
6+
memoizedInsertNode,
7+
} from './memoized-tree-data-utils';
8+
9+
describe('insertNode', () => {
10+
it('should handle empty data', () => {
11+
const params = {
12+
treeData: [],
13+
depth: 0,
14+
minimumTreeIndex: 0,
15+
newNode: {},
16+
getNodeKey: ({ treeIndex }) => treeIndex,
17+
};
18+
19+
expect(insertNode(params) === insertNode(params)).toEqual(false);
20+
expect(memoizedInsertNode(params) === memoizedInsertNode(params)).toEqual(true);
21+
expect(memoizedInsertNode(params) === memoizedInsertNode({...params, treeData: [{}]})).toEqual(false);
22+
});
23+
});

0 commit comments

Comments
 (0)