Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add update #21

Merged
merged 1 commit into from
Mar 5, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/plumbing/core.clj
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,16 @@
(reset! m-atom# (assoc! ~m-sym ~key-expr ~val-expr))))
(persistent! @m-atom#))))

(defn update
"Updates the value in map m at k with the function f.

Like update-in, but for updating a single top-level key.
Any additional args will be passed to f after the value."
([m k f] (assoc m k (f (get m k))))
([m k f x1] (assoc m k (f (get m k) x1)))
([m k f x1 x2] (assoc m k (f (get m k) x1 x2)))
([m k f x1 x2 & xs] (assoc m k (apply f (get m k) x1 x2 xs))))

(defn map-vals
"Build map k -> (f v) for [k v] in map, preserving the initial type"
[f m]
Expand Down
14 changes: 14 additions & 0 deletions test/plumbing/core_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,20 @@
(is (= (count m) 1000))
(is (= (m 999) 499500))))

(deftest update-test
(testing "0 extra args"
(is (= {:a 5, :b 0}
(update {:a 4, :b 0} :a inc)))
(is (= {:a 1}
(update {} :a (fnil inc 0)))))
(testing "1 extra arg"
(is (= {:a 42, :b 0}
(update {:a 6, :b 0} :a * 7)))
(is (= {:a #{42}}
(update {} :a (fnil conj #{}) 42))))
(testing "100 extra args"
(is (= {:a 4951} (apply update {:a 1} :a + (range 100))))))

(deftest map-vals-test
(is (= (map-vals inc {:a 0 :b 0})
{:a 1 :b 1}))
Expand Down