helene
Version:
Real-time Web Apps for Node.js
85 lines • 2.77 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AVLTreeWrapper = void 0;
const avl_1 = require("avl");
class AVLTreeWrapper {
tree;
unique;
compareKeys;
checkValueEquality;
constructor(options) {
this.unique = options.unique;
this.compareKeys = options.compareKeys;
this.checkValueEquality = options.checkValueEquality;
this.tree = new avl_1.AVLTree(this.compareKeys, false);
}
insert(key, value) {
const existingNode = this.tree.find(key);
if (existingNode) {
const existingValues = existingNode.data || [];
if (this.unique) {
throw new Error('Unique Constraint Violation');
}
for (const existingValue of existingValues) {
if (this.checkValueEquality(existingValue, value)) {
return;
}
}
existingValues.push(value);
this.tree.remove(key);
this.tree.insert(key, existingValues);
}
else {
this.tree.insert(key, [value]);
}
}
delete(key, value) {
const node = this.tree.find(key);
if (!node || !node.data)
return;
const values = node.data;
const newValues = values.filter(v => !this.checkValueEquality(v, value));
this.tree.remove(key);
if (newValues.length > 0) {
this.tree.insert(key, newValues);
}
}
search(key) {
const node = this.tree.find(key);
return node ? node.data || [] : [];
}
betweenBounds(query) {
const results = [];
const { $gte, $gt, $lte, $lt } = query;
this.tree.forEach(node => {
if (node.data) {
const key = node.key;
let include = true;
if ($gte !== undefined && this.compareKeys(key, $gte) < 0)
include = false;
if ($gt !== undefined && this.compareKeys(key, $gt) <= 0)
include = false;
if ($lte !== undefined && this.compareKeys(key, $lte) > 0)
include = false;
if ($lt !== undefined && this.compareKeys(key, $lt) >= 0)
include = false;
if (include) {
results.push(...node.data);
}
}
});
return results;
}
executeOnEveryNode(fn) {
this.tree.forEach(node => {
if (node.data) {
fn({ data: node.data });
}
});
}
getNumberOfKeys() {
return this.tree.size;
}
}
exports.AVLTreeWrapper = AVLTreeWrapper;
//# sourceMappingURL=avl-tree-wrapper.js.map