From 426873da982cd3027c91d80422d2697111f2a3c2 Mon Sep 17 00:00:00 2001 From: nathanmarz Date: Sun, 7 May 2017 20:30:50 -0400 Subject: [PATCH] support transforms to NONE for set-elem and map-key --- src/clj/com/rpl/specter.cljc | 21 +++++++++++++++------ test/com/rpl/specter/core_test.cljc | 2 ++ 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/clj/com/rpl/specter.cljc b/src/clj/com/rpl/specter.cljc index 499adc3..8c2e1be 100644 --- a/src/clj/com/rpl/specter.cljc +++ b/src/clj/com/rpl/specter.cljc @@ -870,7 +870,8 @@ (defrichnav ^{:doc "Navigates to the given key in the map (not to the value). Navigates only if the - key currently exists in the map."} + key currently exists in the map. Can transform to NONE to remove the key/value + pair from the map."} map-key [key] (select* [this vals structure next-fn] @@ -881,14 +882,17 @@ (transform* [this vals structure next-fn] (if (contains? structure key) (let [newkey (next-fn vals key) - oldval (get structure key)] - (-> structure (dissoc key) (assoc newkey oldval)) - ) + dissoced (dissoc structure key)] + (if (identical? NONE newkey) + dissoced + (assoc dissoced newkey (get structure key)) + )) structure ))) (defrichnav - ^{:doc "Navigates to the given element in the set only if it exists in the set."} + ^{:doc "Navigates to the given element in the set only if it exists in the set. + Can transform to NONE to remove the element from the set."} set-elem [elem] (select* [this vals structure next-fn] @@ -898,7 +902,12 @@ )) (transform* [this vals structure next-fn] (if (contains? structure elem) - (-> structure (disj elem) (conj (next-fn vals elem))) + (let [newelem (next-fn vals elem) + removed (disj structure elem)] + (if (identical? NONE newelem) + removed + (conj removed newelem) + )) structure ))) diff --git a/test/com/rpl/specter/core_test.cljc b/test/com/rpl/specter/core_test.cljc index dcd9318..253ff2e 100644 --- a/test/com/rpl/specter/core_test.cljc +++ b/test/com/rpl/specter/core_test.cljc @@ -1531,12 +1531,14 @@ (is (= {:c 3} (setval (s/map-key :a) :b {:c 3}))) (is (= {:b 2} (setval (s/map-key :a) :b {:a 2}))) (is (= {:b 2} (setval (s/map-key :a) :b {:a 2 :b 1}))) + (is (= {:b 2} (setval (s/map-key :a) s/NONE {:a 1 :b 2}))) ) (deftest set-elem-test (is (= #{:b :d} (setval (s/set-elem :a) :x #{:b :d}))) (is (= #{:x :a} (setval (s/set-elem :b) :x #{:b :a}))) (is (= #{:a} (setval (s/set-elem :b) :a #{:b :a}))) + (is (= #{:b} (setval (s/set-elem :a) s/NONE #{:a :b}))) ) #?(:clj