Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/medley/core.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 21 additions & 0 deletions test/medley/core_test.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -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]))
Expand Down
Loading