UNPKG

typescript-algorithms-and-datastructures

Version:
67 lines 2.47 kB
(function (factory) { if (typeof module === "object" && typeof module.exports === "object") { var v = factory(require, exports); if (v !== undefined) module.exports = v; } else if (typeof define === "function" && define.amd) { define(["require", "exports"], factory); } })(function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class RadixTreeNode { constructor(word, value) { this.children = []; this.word = word; this.value = value; } addChild(child) { return this.children.push(child); } isLeaf() { return this.value !== null; } getNodeWithSharedPrefix(prefix) { const partialMatch = this.children.filter(node => node.word[0] === prefix[0]); if (partialMatch.length === 0) { return null; } return partialMatch[0]; } getCommonPrefix(prefix) { let i = 0; let commonPrefix = ""; while (prefix[i] === this.word[i]) { commonPrefix += prefix[i]; i++; } return commonPrefix; } splitNode(sufix) { const commonPrefix = this.getCommonPrefix(sufix); const currentChildren = this.children.slice(0); const newNode = new RadixTreeNode(this.word.substr(commonPrefix.length), this.value); currentChildren.forEach(newNode.addChild, newNode); this.word = commonPrefix; this.value = null; this.children = [newNode]; } selectNextNodeFromPrefix(prefix) { const exactMatch = this.children.filter(node => node.word === prefix); if (exactMatch.length === 1) { return exactMatch[0]; } const partialMatch = this.children.filter(node => node.word[0] === prefix[0]); if (partialMatch.length === 0) { return null; } const partialMatchWord = partialMatch[0].word; if (prefix.indexOf(partialMatchWord) === -1) { return null; } return partialMatch[0]; } } exports.RadixTreeNode = RadixTreeNode; }); //# sourceMappingURL=RadixTreeNode.js.map