UNPKG

@kamilmielnik/trie

Version:

Trie data structure implementation in TypeScript. Highly performant. No dependencies. Built for a Scrabble Solver.

52 lines (51 loc) 2.04 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.traverse = void 0; const nodeKeyComparator_1 = require("./nodeKeyComparator"); /** * Visits every descendant {@link Node} of given {@link Node} and calls a callback. * * @param node - {@link Node} to look for descendant {@link Node | Nodes} in. * @param callback - Callback that will be called for each visited {@link Node}. Return true from callback to stop traversing. * @param options - See {@link TraverseOptions}. */ const traverse = (node, callback, options = {}) => { const stack = []; let currentKeyIndex = 0; let currentNode = node; let currentPrefix = options.prefix || ''; while (stack.length > 0 || currentNode) { while (currentNode) { const keys = Object.keys(currentNode); if (currentKeyIndex >= keys.length) { currentNode = undefined; } else { const sortedKeys = options.sort ? keys.sort(nodeKeyComparator_1.nodeKeyComparator) : keys; const key = sortedKeys[currentKeyIndex]; if (key === 'wordEnd') { ++currentKeyIndex; } else { stack.push({ keyIndex: currentKeyIndex, node: currentNode }); currentKeyIndex = 0; currentNode = currentNode[key]; currentPrefix += key; if (!options.wordsOnly || currentNode.wordEnd) { const shouldStop = callback({ node: currentNode, prefix: currentPrefix }); if (shouldStop) { return; } } } } } if (stack.length > 0) { const state = stack.pop(); currentKeyIndex = state.keyIndex + 1; currentNode = state.node; currentPrefix = currentPrefix.slice(0, -1); } } }; exports.traverse = traverse;