Skip to content

Instantly share code, notes, and snippets.

@helabenkhalfallah
Last active February 11, 2024 20:21
Show Gist options
  • Save helabenkhalfallah/e0f040b113559d49adab2f4785c99d6a to your computer and use it in GitHub Desktop.
Save helabenkhalfallah/e0f040b113559d49adab2f4785c99d6a to your computer and use it in GitHub Desktop.
BTreeNode
class BTreeNode {
constructor(isLeaf) {
/**
* @type {number[]} list of values in the node
*/
this.values = [];
/**
* @type {boolean} is a leaf
*/
this.leaf = isLeaf;
/**
* @type {BTreeNode[]}
*/
this.children = [];
/**
* Reference to the tree its belong.
* @type {BTree}
*/
this.tree = null;
/**
* @type {BTreeNode}
*/
this.parent = null;
}
/**
* Number of values
* @returns {number}
*/
get n() {
return this.values.length;
}
/**
* Add value
* @param {number} value
* @param {number} pos
*/
addValue(value) {
if (!value) {
return;
}
let pos = 0;
while (pos < this.n && this.values[pos] < value) {
pos++;
}
this.values.splice(pos, 0, value);
}
/**
* Delete value and return it
* @param {number} pos position
* @return {number}
*/
removeValue(pos) {
if (pos >= this.n) {
return null;
}
return this.values.splice(pos, 1)[0];
}
/**
* Add child node at position pos
* @param {BTreeNode} node
* @param {number} pos
*/
addChild(node, pos) {
this.children.splice(pos, 0, node);
node.parent = this;
}
/**
* Delete node from position and return it
* @param {number} pos
* @return {BTreeNode}
*/
deleteChild(pos) {
return this.children.splice(pos, 1)[0];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment