tstruct
Version:
Data structures & basic algorithms library
85 lines (84 loc) • 2.79 kB
JavaScript
;
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Trie = void 0;
var Trie = (function () {
function Trie() {
this._map = new Map();
}
Trie.prototype.add = function (word) {
if (word.length <= 0)
return;
var map = this._map;
for (var i = 0; i < word.length; i++) {
var c = word[i];
if (!map.has(c)) {
var children = new Map();
map.set(c, {
value: c,
children: children,
isWord: i == word.length - 1,
});
map = children;
}
else {
map = map.get(c).children;
}
}
};
Trie.prototype.exists = function (word) {
var leaf = this.findLeaf(word);
return leaf != undefined && leaf.isWord ? true : false;
};
Trie.prototype.findLeaf = function (word, map) {
if (map === void 0) { map = this._map; }
var char = word[0];
if (!map.has(char))
return;
if (word.length == 1) {
return map.get(char);
}
return this.findLeaf(word.substr(1), map.get(char).children);
};
Trie.prototype.complete = function (word) {
var result = [];
var leaf = this.findLeaf(word);
if (leaf == undefined)
return result;
this._complete(leaf, word, result);
return result;
};
Trie.prototype._complete = function (node, word, result) {
var e_1, _a;
if (word === void 0) { word = ""; }
if (result === void 0) { result = []; }
if (node.isWord) {
result.push(word);
}
try {
for (var _b = __values(node.children), _c = _b.next(); !_c.done; _c = _b.next()) {
var n = _c.value;
this._complete(n[1], word + n[0], result);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
};
return Trie;
}());
exports.Trie = Trie;