Skip to content

Commit 4e48a34

Browse files
thomasmulvaneyswannodette
authored andcommitted
CLJS-2112: Iterator based reduce path
Introduces iter-reduce to support reduction of iterable collections efficiently.
1 parent 43a3443 commit 4e48a34

File tree

1 file changed

+31
-2
lines changed

1 file changed

+31
-2
lines changed

src/main/cljs/cljs/core.cljs

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2373,6 +2373,29 @@ reduces them without incurring seq initialization"
23732373
(garray/shuffle a)
23742374
(vec a)))
23752375

2376+
(defn- iter-reduce
2377+
([coll f]
2378+
(let [iter (-iterator coll)]
2379+
(if (.hasNext iter)
2380+
(let [init (.next iter)]
2381+
(loop [acc init]
2382+
(if (.hasNext iter)
2383+
(let [nacc (f acc (.next iter))]
2384+
(if (reduced? nacc)
2385+
@nacc
2386+
(recur nacc)))
2387+
acc)))
2388+
(f))))
2389+
([coll f init]
2390+
(let [iter (-iterator coll)]
2391+
(loop [acc init]
2392+
(if (.hasNext iter)
2393+
(let [nacc (f acc (.next iter))]
2394+
(if (reduced? nacc)
2395+
@nacc
2396+
(recur nacc)))
2397+
acc)))))
2398+
23762399
(defn reduce
23772400
"f should be a function of 2 arguments. If val is not supplied,
23782401
returns the result of applying f to the first 2 items in coll, then
@@ -2397,6 +2420,9 @@ reduces them without incurring seq initialization"
23972420
(native-satisfies? IReduce coll)
23982421
(-reduce coll f)
23992422

2423+
(iterable? coll)
2424+
(iter-reduce coll f)
2425+
24002426
:else
24012427
(seq-reduce f coll)))
24022428
([f val coll]
@@ -2413,6 +2439,9 @@ reduces them without incurring seq initialization"
24132439
(native-satisfies? IReduce coll)
24142440
(-reduce coll f val)
24152441

2442+
(iterable? coll)
2443+
(iter-reduce coll f val)
2444+
24162445
:else
24172446
(seq-reduce f val coll))))
24182447

@@ -6505,9 +6534,9 @@ reduces them without incurring seq initialization"
65056534

65066535
IReduce
65076536
(-reduce [coll f]
6508-
(seq-reduce f coll))
6537+
(iter-reduce coll f))
65096538
(-reduce [coll f start]
6510-
(seq-reduce f start coll))
6539+
(iter-reduce coll f start))
65116540

65126541
IFn
65136542
(-invoke [coll k]

0 commit comments

Comments
 (0)