Skip to content

Commit

Permalink
Add find-in function
Browse files Browse the repository at this point in the history
  • Loading branch information
weavejester committed Oct 19, 2024
1 parent b2dd5d0 commit 7c36bc6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/medley/core.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -667,3 +667,13 @@
(when (some? coll)
(let [index (.indexOf coll item)]
(when-not (neg? index) index))))

(defn find-in
"Similar to `clojure.core/find`, except that it finds a key/value pair in an
nested associate structure `m`, given a sequence of keys `ks`. See also:
`clojure.core/get-in`."
{:added "1.9.0"}
[m ks]
(if (next ks)
(-> (get-in m (butlast ks)) (find (last ks)))
(find m (first ks))))
9 changes: 9 additions & 0 deletions test/medley/core_test.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -516,3 +516,12 @@

(is (= 1 (m/index-of (range 0 10) 1)))
(is (= 1 (m/index-of (map str [:a :b]) ":b"))))

(deftest test-find-in
(is (nil? (m/find-in {} [:a])))
(is (nil? (m/find-in {} [:a :b])))
(is (nil? (m/find-in {:a {}} [:a :b])))
(is (= [:a 1] (m/find-in {:a 1} [:a])))
(is (= [:b 2] (m/find-in {:a {:b 2}} [:a :b])))
(is (= [:b {:c 3}] (m/find-in {:a {:b {:c 3}}} [:a :b])))
(is (= [:c 3] (m/find-in {:a {:b {:c 3}}} [:a :b :c]))))

0 comments on commit 7c36bc6

Please sign in to comment.