Skip to content

Commit c71484f

Browse files
committed
Add map-nth.
1 parent a70dab5 commit c71484f

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

src/useful/seq.clj

+10
Original file line numberDiff line numberDiff line change
@@ -359,3 +359,13 @@ ineligible for garbage collection."
359359
(let [x (first coll)]
360360
(cons x (when-not (pred x)
361361
(take-until pred (rest coll))))))))
362+
363+
(defn map-nth
364+
"Calls f on every nth element of coll. If start is passed, starts
365+
at that element (counting from zero), otherwise starts with zero."
366+
([f nth coll] (map-nth f 0 nth coll))
367+
([f start nth coll]
368+
(map #(% %2)
369+
(concat (repeat start identity)
370+
(cycle (cons f (repeat (dec nth) identity))))
371+
coll)))

test/useful/seq_test.clj

+5
Original file line numberDiff line numberDiff line change
@@ -178,3 +178,8 @@
178178
s (sequeue 2 coll)]
179179
(is (= 1 (first s)))
180180
(is (thrown? Throwable (dorun s))))))
181+
182+
(deftest test-map-nth
183+
(is (= [2 2 4 4 6 6 8 8 10 10]
184+
(map-nth inc 2 [1 2 3 4 5 6 7 8 9 10])))
185+
(is (= ["" "x" "" "x"] (map-nth #(str % "x") 1 2 ["" "" "" ""]))))

0 commit comments

Comments
 (0)