Skip to content

Commit 3a6fd9c

Browse files
committed
Add map-padded
1 parent 54f45ab commit 3a6fd9c

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

src/medley/core.cljc

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -706,3 +706,25 @@
706706
(if (next ks)
707707
(-> (get-in m (butlast ks)) (find (last ks)))
708708
(find m (first ks))))
709+
710+
(defn map-padded
711+
[f pad & colls]
712+
(let [pad-seq (repeat pad)
713+
active-cnt (volatile! (count colls))
714+
iter-colls
715+
(fn [colls]
716+
(mapv (fn [coll]
717+
(or (seq coll)
718+
(do (vswap! active-cnt unchecked-dec)
719+
pad-seq)))
720+
colls))
721+
iterators (iter-colls colls)]
722+
(if (zero? @active-cnt)
723+
()
724+
(let [step (fn step [colls]
725+
(lazy-seq
726+
(let [colls (iter-colls colls)]
727+
(when (pos? @active-cnt)
728+
(cons (apply f (mapv first colls))
729+
(step (mapv rest colls)))))))]
730+
(step iterators)))))

test/medley/core_test.cljc

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -547,3 +547,28 @@
547547
(is (= [:b 2] (m/find-in {:a {:b 2}} [:a :b])))
548548
(is (= [:b {:c 3}] (m/find-in {:a {:b {:c 3}}} [:a :b])))
549549
(is (= [:c 3] (m/find-in {:a {:b {:c 3}}} [:a :b :c]))))
550+
551+
(deftest test-map-padded
552+
(is (= (map + (range 3) (range 4) (range 5) (range 10))
553+
[0 4 8]
554+
(take 3 (m/map-padded + 0 (range 3) (range 4) (range 5) (range 10)))))
555+
(is (= [0 4 8 19 28 35 36 37 38 39]
556+
(m/map-padded + 10 (range 3) (range 4) (range 5) (range 10))))
557+
(is (= ()
558+
(m/map-padded + 10 () () ())))
559+
(testing "laziness"
560+
(let [state (volatile! [])]
561+
(is (= [0 4 8 19 28]
562+
(take 5 (m/map-padded (fn [a b c d]
563+
(vswap! state conj [a b c d])
564+
(+ a b c d))
565+
10
566+
(range 3) (range 4) (range 5) (range 10)))))
567+
(is (= [[0 0 0 0] [1 1 1 1] [2 2 2 2] [10 3 3 3] [10 10 4 4]]
568+
@state))))
569+
(testing "handles sequences with nils"
570+
(is (= [[nil 0 0 0] [nil 1 1 1] [nil 2 2 2]
571+
[:missing 3 3 3]
572+
[:missing :missing 4 4]
573+
[:missing :missing :missing 5]]
574+
(take 6 (m/map-padded vector :missing [nil nil nil] (range 4) (range 5) (range 10)))))))

0 commit comments

Comments
 (0)