sonic-forest
Version:
High-performance (binary) tree and sorted map implementation (AVL, Splay, Radix, Red-Black)
58 lines (57 loc) • 2.01 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.BinaryTrieNode = void 0;
const util_1 = require("../util");
class BinaryTrieNode {
constructor(k, v) {
this.k = k;
this.v = v;
this.p = undefined;
this.l = undefined;
this.r = undefined;
this.children = undefined;
}
forChildren(callback) {
let child = (0, util_1.first)(this.children);
let i = 0;
while (child) {
callback(child, i);
i++;
child = (0, util_1.next)(child);
}
}
toRecord(prefix, record) {
if (!record)
record = {};
const currentPrefix = prefix ? new Uint8Array([...prefix, ...this.k.toUint8Array()]) : this.k.toUint8Array();
if (this.v !== undefined) {
const key = Array.from(currentPrefix).join(',');
record[key] = this.v;
}
let child = (0, util_1.first)(this.children);
while (child) {
child.toRecord(currentPrefix, record);
child = (0, util_1.next)(child);
}
return record;
}
toString(tab = '') {
const value = this.v === undefined ? '' : ` = ${JSON.stringify(this.v)}`;
const childrenNodes = [];
this.forChildren((child) => childrenNodes.push(child));
let result = `${this.constructor.name} ${this.k.toString()}${value}`;
if (childrenNodes.length > 0) {
result += '\n';
childrenNodes.forEach((child, index) => {
const isLast = index === childrenNodes.length - 1;
const prefix = isLast ? '└── ' : '├── ';
const childTab = tab + (isLast ? ' ' : '│ ');
result += tab + prefix + child.toString(childTab).replace(/\n/g, '\n' + childTab);
if (!isLast)
result += '\n';
});
}
return result;
}
}
exports.BinaryTrieNode = BinaryTrieNode;