|
| 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 | +} |
0 commit comments