1
0
mirror of https://github.com/JustinSDK/dotSCAD.git synced 2025-04-22 15:12:01 +02:00

add hashmap del get

This commit is contained in:
Justin Lin 2021-03-06 15:40:16 +08:00
parent e27759e8ed
commit 19a02d8f2b
3 changed files with 38 additions and 0 deletions

@ -0,0 +1,18 @@
use <../__comm__/_str_hash.scad>;
use <../util/slice.scad>;
use <../util/find_index.scad>;
function hashmap_del(map, key, eq = function(e1, e2) e1 == e2, hash = function(e) _str_hash(e)) =
let(
bidx = hash(key) % len(map),
bucket = map[bidx],
leng = len(bucket)
)
leng == 0 ? map :
let(i = find_index(bucket, function(e) eq(e[0], key)))
i == -1 ? map :
concat(
slice(map, 0, bidx),
[concat(slice(bucket, 0, i), slice(bucket, i + 1))],
slice(map, bidx + 1)
);

@ -0,0 +1,11 @@
use <../__comm__/_str_hash.scad>;
use <../util/slice.scad>;
use <../util/find_index.scad>;
function hashmap_get(map, key, eq = function(e1, e2) e1 == e2, hash = function(e) _str_hash(e)) =
let(
bidx = hash(key) % len(map),
bucket = map[bidx]
)
let(i = find_index(bucket, function(e) eq(e[0], key)))
i == -1 ? undef : bucket[i][1];

@ -3,6 +3,8 @@ use <collection/hashmap.scad>;
use <collection/hashmap_list.scad>;
use <collection/hashmap_add.scad>;
use <collection/hashmap_len.scad>;
use <collection/hashmap_del.scad>;
use <collection/hashmap_get.scad>;
module test_hashmap() {
echo("==== test_hashmap ====");
@ -23,6 +25,13 @@ module test_hashmap() {
s3 = hashmap_add(s2, "k5678", 200);
assert(hashmap_list(s3) == [["k9876", 3], ["k4444", 3], ["k1234", 1], ["k5678", 200], ["k1357", 100]]);
s4 = hashmap_del(s3, "k4444");
assert(hashmap_list(s4) == [["k9876", 3], ["k1234", 1], ["k5678", 200], ["k1357", 100]]);
assert(hashmap_list(hashmap_del(s4, "k4444")) == [["k9876", 3], ["k1234", 1], ["k5678", 200], ["k1357", 100]]);
assert(hashmap_get(s4, "k1234") == 1);
assert(hashmap_get(s4, "k0000") == undef);
}
test_hashmap();