From 30aa73eff8284de5aadf089547c8ceba0f72021b Mon Sep 17 00:00:00 2001 From: Tom Dalziel Date: Tue, 24 Jun 2025 12:33:08 +0100 Subject: [PATCH] Add mapcat-indexed function --- src/medley/core.cljc | 15 +++++++++++++++ test/medley/core_test.cljc | 21 +++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/medley/core.cljc b/src/medley/core.cljc index 256df99..dc4eb37 100644 --- a/src/medley/core.cljc +++ b/src/medley/core.cljc @@ -550,6 +550,21 @@ ([coll] (map-indexed vector coll))) +(defn mapcat-indexed + "Returns the result of applying concat to the result of applying f to 0 and + the first item of coll, followed by applying f to 1 and the second item in + coll, etc, until coll is exhausted. Thus function f should accept 2 arguments, + index and item. Returns a stateful transducer when no collection is provided." + ([f] + (comp (map-indexed f) cat)) + ([f coll] + (letfn [(mapci [idx coll] + (lazy-seq + (when-let [s (seq coll)] + (concat (f idx (first s)) + (mapci (inc idx) (rest s))))))] + (mapci 0 coll)))) + (defn insert-nth "Returns a lazy sequence of the items in coll, with a new item inserted at the supplied index, followed by all subsequent items of the collection. Runs diff --git a/test/medley/core_test.cljc b/test/medley/core_test.cljc index 2f5b70c..f0eaa3f 100644 --- a/test/medley/core_test.cljc +++ b/test/medley/core_test.cljc @@ -433,6 +433,27 @@ (is (= (into [] (m/indexed) []) [])))) +(deftest test-mapcat-indexed + (testing "sequences" + (is (= (m/mapcat-indexed vector nil) + [])) + (is (= (m/mapcat-indexed vector []) + [])) + (is (= (m/mapcat-indexed repeat [:a :b :c :d]) + [:b :c :c :d :d :d])) + (is (= (m/mapcat-indexed repeat []) + []))) + + (testing "transducers" + (is (= (into [] (m/mapcat-indexed vector) nil) + [])) + (is (= (into [] (m/mapcat-indexed vector) []) + [])) + (is (= (into [] (m/mapcat-indexed repeat) [:a :b :c :d]) + [:b :c :c :d :d :d])) + (is (= (into [] (m/mapcat-indexed repeat) []) + [])))) + (deftest test-insert-nth (testing "sequences" (is (= (m/insert-nth 0 :a [1 2 3 4]) [:a 1 2 3 4]))