From e4a3275ff1d8ae799904ba8941c36f36d80a84d0 Mon Sep 17 00:00:00 2001 From: Nathan Marz Date: Fri, 19 Jun 2015 14:13:22 -0400 Subject: [PATCH] change cond-path/if-path to take a selector for the conditional (works like selected?) --- src/clj/com/rpl/specter.clj | 4 ++-- src/clj/com/rpl/specter/impl.clj | 8 +++++++- test/clj/com/rpl/specter/core_test.clj | 27 ++++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/src/clj/com/rpl/specter.clj b/src/clj/com/rpl/specter.clj index ebab51e..76bd863 100644 --- a/src/clj/com/rpl/specter.clj +++ b/src/clj/com/rpl/specter.clj @@ -192,7 +192,7 @@ [& conds] (->> conds (partition 2) - (map (fn [[c p]] [c (comp-paths* p)])) + (map (fn [[c p]] [(comp-paths* c) (comp-paths* p)])) doall ->ConditionalPath )) @@ -201,4 +201,4 @@ "Like cond-path, but with if semantics." ([cond-fn if-path] (cond-path cond-fn if-path)) ([cond-fn if-path else-path] - (cond-path cond-fn if-path (fn [_] true) else-path))) + (cond-path cond-fn if-path nil else-path))) diff --git a/src/clj/com/rpl/specter/impl.clj b/src/clj/com/rpl/specter/impl.clj index 03df7a4..14e6d99 100644 --- a/src/clj/com/rpl/specter/impl.clj +++ b/src/clj/com/rpl/specter/impl.clj @@ -189,6 +189,9 @@ )))) (extend-protocol StructureValsPathComposer + nil + (comp-paths* [sp] + (coerce-path sp)) Object (comp-paths* [sp] (coerce-path sp)) @@ -486,7 +489,10 @@ (defn- retrieve-selector [cond-pairs structure] (->> cond-pairs - (drop-while (fn [[c-fn _]] (not (c-fn structure)))) + (drop-while (fn [[c-selector _]] + (->> structure + (compiled-select* c-selector) + empty?))) first second )) diff --git a/test/clj/com/rpl/specter/core_test.clj b/test/clj/com/rpl/specter/core_test.clj index c4a7740..54e0a9f 100644 --- a/test/clj/com/rpl/specter/core_test.clj +++ b/test/clj/com/rpl/specter/core_test.clj @@ -2,6 +2,7 @@ (:use [clojure.test] [clojure.test.check.clojure-test] [com.rpl specter] + [com.rpl.specter protocols] [com.rpl.specter test-helpers]) (:require [clojure.test.check [generators :as gen] @@ -235,6 +236,9 @@ (and (= [i] (select nil i)) (= (afn i) (update nil afn i))))) +(deftest nil-comp-test + (is (= [5] (select (comp-paths* nil) 5)))) + (defspec putval-test (for-all+ [kw gen/keyword @@ -315,3 +319,26 @@ * 2))) ) + +(defspec cond-path-selector-test + (for-all+ + [k1 (max-size 3 gen/keyword) + k2 (max-size 3 gen/keyword) + k3 (max-size 3 gen/keyword) + m (max-size 5 + (gen-map-with-keys + gen/keyword + gen/int + k1 + k2 + k3)) + pred (gen/elements [odd? even?]) + ] + (let [v1 (get m k1) + k (if (pred v1) k2 k3)] + (and + (= (update (if-path [k1 pred] k2 k3) inc m) + (update k inc m)) + (= (select (if-path [k1 pred] k2 k3) m) + (select k m)) + ))))