Skip to content

Commit 1992641

Browse files
authored
Merge pull request #118 from clojure/cljs-3331/update-keys-vals
CLJS-3331: add update-vals / keys
2 parents 8a7b907 + 3f199d9 commit 1992641

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

src/main/cljs/cljs/core.cljs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11724,6 +11724,35 @@ reduces them without incurring seq initialization"
1172411724
(tap x)
1172511725
(catch js/Error ex))))))
1172611726

11727+
(defn update-vals
11728+
"m f => {k (f v) ...}
11729+
Given a map m and a function f of 1-argument, returns a new map where the keys of m
11730+
are mapped to result of applying f to the corresponding values of m."
11731+
{:added "1.11"}
11732+
[m f]
11733+
(with-meta
11734+
(persistent!
11735+
(reduce-kv (fn [acc k v] (assoc! acc k (f v)))
11736+
(if (implements? IEditableCollection m)
11737+
(transient m)
11738+
(transient {}))
11739+
m))
11740+
(meta m)))
11741+
11742+
(defn update-keys
11743+
"m f => {(f k) v ...}
11744+
Given a map m and a function f of 1-argument, returns a new map whose
11745+
keys are the result of applying f to the keys of m, mapped to the
11746+
corresponding values of m.
11747+
f must return a unique key for each key of m, else the behavior is undefined."
11748+
{:added "1.11"}
11749+
[m f]
11750+
(let [ret (persistent!
11751+
(reduce-kv (fn [acc k v] (assoc! acc (f k) v))
11752+
(transient {})
11753+
m))]
11754+
(with-meta ret (meta m))))
11755+
1172711756
;; -----------------------------------------------------------------------------
1172811757
;; Bootstrap helpers - incompatible with advanced compilation
1172911758

src/test/cljs/cljs/core_test.cljs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1883,3 +1883,21 @@
18831883
(is (exists? /))
18841884
(is (exists? cljs.core//))
18851885
(is (not (exists? cljs.core-test//))))
1886+
1887+
(deftest test-update-vals
1888+
(let [inm (with-meta {:a 1 :b 2} {:has :meta})]
1889+
(are [result expr] (= result expr)
1890+
{:a 2 :b 3} (update-vals inm inc)
1891+
{:has :meta} (meta (update-vals inm inc))
1892+
{0 2 2 4} (update-vals (hash-map 0 1 2 3) inc)
1893+
{0 2 2 4} (update-vals (array-map 0 1 2 3) inc)
1894+
{0 2 2 4} (update-vals (sorted-map 2 3 0 1) inc))))
1895+
1896+
(deftest test-update-keys
1897+
(let [inm (with-meta {:a 1 :b 2} {:has :meta})]
1898+
(are [result expr] (= result expr)
1899+
{"a" 1 "b" 2} (update-keys inm name)
1900+
{:has :meta} (meta (update-keys inm name))
1901+
{1 1 3 3} (update-keys (hash-map 0 1 2 3) inc)
1902+
{1 1 3 3} (update-keys (array-map 0 1 2 3) inc)
1903+
{1 1 3 3} (update-keys (sorted-map 2 3 0 1) inc))))

0 commit comments

Comments
 (0)