@kamilmielnik/trie
Version:
Trie data structure implementation in TypeScript. Highly performant. No dependencies. Built for a Scrabble Solver.
51 lines (50 loc) • 1.62 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.deserialize = void 0;
const constants_1 = require("../constants");
/**
* Creates a new {@link Node} by deserializing given string.
*
* The inverse of {@link serialize}.
*
* @param serialized - String with value returned by {@link serialize}.
* @returns Instance of a root {@link Node} of deserialized string.
*/
const deserialize = (serialized) => {
const stack = [];
let node = {};
let i = 1;
while (i < serialized.length - 1) {
const character = serialized[i];
const nextCharacter = serialized[i + 1];
++i;
if (character === constants_1.CLOSE_PARENS) {
const nextNode = stack.pop();
if (!nextNode) {
throw new Error(`Syntax error: misplaced "${constants_1.CLOSE_PARENS}"`);
}
node = nextNode;
}
else if (nextCharacter === constants_1.CLOSE_PARENS) {
node[character] = { wordEnd: true };
const nextNode = stack.pop();
if (!nextNode) {
throw new Error(`Syntax error: misplaced "${constants_1.CLOSE_PARENS}"`);
}
node = nextNode;
++i;
}
else if (nextCharacter === constants_1.OPEN_PARENS) {
stack.push(node);
const newNode = node[character] || {};
node[character] = newNode;
node = newNode;
++i;
}
else {
node[character] = { wordEnd: true };
}
}
return node;
};
exports.deserialize = deserialize;