feat: add Map.merge (#1106)

* feat: add Map.merge

* refactor: simplify ref in Map.merge
This commit is contained in:
Veit Heller 2021-01-03 13:20:46 +01:00 committed by GitHub
parent 1607af1d6a
commit ff30fbc26e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 17 additions and 7 deletions

View File

@ -226,16 +226,22 @@
m
(resize m new-size))))
(doc contains? "Check whether the map m contains the key k.")
(defn contains? [m k]
(let [idx (Int.positive-mod (hash k) @(n-buckets m))]
(Bucket.contains? (Array.unsafe-nth (buckets m) idx) k)))
(doc put "Put a value v into map m, using the key k.")
(defn put [m k v]
(if (> (/ (* @(len &m) 100) @(n-buckets &m)) min-load)
(put (grow m) k v)
(let [idx (Int.positive-mod (hash k) @(n-buckets &m))]
(let [idx (Int.positive-mod (hash k) @(n-buckets &m))
in? (contains? &m k)]
(update-len
(update-buckets m &(fn [b]
(let [n (Array.unsafe-nth &b idx)]
(Array.aset b idx (Bucket.put @n k v)))))
&Int.inc))))
&(if in? id Int.inc)))))
(doc put! "Put a value v into map m, using the key k, in place.")
(defn put! [m k v]
@ -284,11 +290,6 @@
(defn empty? [m]
(= @(len m) 0))
(doc contains? "Check whether the map m contains the key k.")
(defn contains? [m k]
(let [idx (Int.positive-mod (hash k) @(n-buckets m))]
(Bucket.contains? (Array.unsafe-nth (buckets m) idx) k)))
(doc remove "Remove the value under the key k from the map m.")
(defn remove [m k]
(if (> (/ (* @(len &m) 100) @(n-buckets &m)) min-load)
@ -354,6 +355,10 @@
(set! init (~f init (Pair.a e) (Pair.b e)))))))
init))
(doc merge "Merge two maps `m1` and `m2`. On collision the value from `m2` is preferred.")
(defn merge [m1 m2]
(kv-reduce &(fn [m k v] (put m k v)) m1 m2))
(doc vals "Return an array of the values of the map. Order corresponds to order of (keys m)")
(defn vals [m]
(kv-reduce &(fn [arr _ v] (Array.push-back arr @v))

View File

@ -209,6 +209,11 @@
&(Map.reverse &{@"hi" 1 @"bye" 2})
"reverse works"
)
(assert-equal test
&{1 @"hi" 2 @"bye" 3 @"!"}
&(Map.merge {1 @"bye" 3 @"!"} &{2 @"bye" 1 @"hi"})
"merge works"
)
(assert-true test
(let-do [s (Set.create)]
(Set.put! &s "1")