Skip to content

Commit

Permalink
Add clear() API, which removes all entries from the BTree
Browse files Browse the repository at this point in the history
  • Loading branch information
ByronBecker committed Jan 1, 2024
1 parent bb5daa2 commit e1f47d9
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/BTree.mo
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,17 @@ module {
order = btreeOrder;
}
};

/// Clears all entries from a BTree
public func clear<K, V>(tree: BTree<K, V>): () {
tree.root := #leaf({
data = {
kvs = Array.tabulateVar<?(K, V)>(tree.order - 1, func(i) { null });
var count = 0;
};
});
tree.size := 0;
};

/// Allows one to quickly create a BTree from an array of key value pairs
public func fromArray<K, V>(order: Nat, compare: (K, K) -> O.Order, kvPairs: [(K, V)]): BTree<K, V> {
Expand Down
38 changes: 38 additions & 0 deletions test/BTreeTest.mo
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,43 @@ let initSuite = S.suite("init", [
*/
]);

let clearSuite = S.suite("clear", [
S.test("on an empty BTree, returns an empty BTree",
do {
let bt = BT.init<Nat, Nat>(?4);
BT.clear<Nat, Nat>(bt);
bt;
},
M.equals(testableNatBTree({
var root = #leaf({
data = {
kvs = [var null, null, null];
var count = 0;
}
});
var size = 0;
order = 4;
}))
),
S.test("on a BTree with elements, returns an empty BTree",
do {
let bt = quickCreateBTreeWithKVPairs(4, [2, 4, 6]);
BT.clear<Nat, Nat>(bt);
bt;
},
M.equals(testableNatBTree({
var root = #leaf({
data = {
kvs = [var null, null, null];
var count = 0;
}
});
var size = 0;
order = 4;
}))
)
]);

let getSuite = S.suite("get", [
S.test("returns null on an empty BTree",
BT.get<Nat, Nat>(BT.init<Nat, Nat>(?4), Nat.compare, 5),
Expand Down Expand Up @@ -4459,6 +4496,7 @@ let maxSuite = S.suite("max", [
S.run(S.suite("BTree",
[
initSuite,
clearSuite,
getSuite,
insertSuite,
substituteKeySuite,
Expand Down

0 comments on commit e1f47d9

Please sign in to comment.