add a submap path

This commit is contained in:
Beau Fabry 2016-04-19 15:15:06 -07:00
parent e1c63e51d3
commit b3c707092e
2 changed files with 31 additions and 0 deletions

View file

@ -217,6 +217,25 @@
(set/union newset))
)))
(defpath
submap*
[m-keys]
(select* [this structure next-fn]
(next-fn (merge (zipmap m-keys (repeat nil)) (select-keys structure m-keys))))
(transform* [this structure next-fn]
(let [submap (merge (zipmap m-keys (repeat nil)) (select-keys structure m-keys))
newmap (next-fn submap)]
(merge (apply dissoc structure m-keys)
newmap))))
(defn submap
"Navigates to the specified submap (by attempting a get for each key).
In a transform, that submap in the original map is changed to the new
value of the submap."
[& m-keys]
(submap* m-keys))
(defpath
walker
[afn]

View file

@ -573,6 +573,18 @@
(= (s/setval (s/subset s3) s4 combined) (-> combined (set/difference s2) (set/union s4)))
))))
(deftest submap-test
(is (= [{:foo 1, :baz nil}]
(s/select [(s/submap :foo :baz)] {:foo 1 :bar 2})))
(is (= {:foo 1, :barry 1}
(s/setval [(s/submap :bar)] {:barry 1} {:foo 1 :bar 2})))
(is (= {:bar 1, :foo 2, :baz nil}
(s/transform [(s/submap :foo :baz) s/ALL s/LAST (comp not nil?)] inc {:foo 1 :bar 1})))
(is (= {:a {:new 1}
:c {:new 1
:old 1}}
(s/setval [s/ALL s/LAST (s/submap)] {:new 1} {:a nil, :c {:old 1}}))))
(deftest nil->val-test
(is (= {:a #{:b}}
(s/setval [:a s/NIL->SET (s/subset #{})] #{:b} nil)))