markov-coil
Version:
Markov chain optimized for large bodies of text.
49 lines (48 loc) • 1.65 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.serialize = serialize;
exports.deserialize = deserialize;
const MarkovCoil_1 = require("./MarkovCoil");
function serializeTrie(node) {
if (node.children.size === 0) {
return [node.weight, 0];
}
const serializedChildren = [];
for (const key of node.children.keys()) {
serializedChildren.push(key);
serializedChildren.push(serializeTrie(node.children.get(key)));
}
return [node.weight, serializedChildren];
}
function deserializeTrie(node) {
if (node[1] === 0) {
const result = new MarkovCoil_1.MarkovNode();
result.weight = Number(node[0]);
result.children = new Map();
return result;
}
const result = new MarkovCoil_1.MarkovNode();
result.weight = Number(node[0]);
const serializedChildren = node[1];
for (let i = 0; i < serializedChildren.length - 1; i += 2) {
const index = serializedChildren[i];
const children = deserializeTrie(serializedChildren[i + 1]);
result.children.set(index, children);
}
return result;
}
function serialize(markov) {
const encodedRoot = serializeTrie(markov.root);
return JSON.stringify([markov.depth, markov.vocab.tokens, encodedRoot]);
}
function deserialize(json) {
const markov = new MarkovCoil_1.MarkovCoil([]);
const data = JSON.parse(json);
markov.depth = data[0];
markov.vocab.tokens = data[1];
markov.vocab.tokens.forEach((token, index) => {
markov.vocab.indexes.set(token, index);
});
markov.root = deserializeTrie(data[2]);
return markov;
}