Skip to content

Commit 7f8fd02

Browse files
author
kutyel
committed
Add reduceWithIndex for Arrays
1 parent dea9663 commit 7f8fd02

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

jscomp/others/belt_Array.ml

+10
Original file line numberDiff line numberDiff line change
@@ -362,6 +362,16 @@ let reduceReverse2U a b x f =
362362
let reduceReverse2 a b x f =
363363
reduceReverse2U a b x (fun [@bs] a b c -> f a b c)
364364

365+
let rec reduceWithIndexAuxU a acc f i =
366+
match a with
367+
| [] -> acc
368+
| x::xs -> reduceWithIndexAuxU xs ((f acc x i)[@bs]) f (i + 1)
369+
370+
let reduceWithIndexU a acc f = reduceWithIndexAuxU a acc f 0
371+
372+
let reduceWithIndex a acc f =
373+
reduceWithIndexU a acc (fun [@bs] acc x i -> f acc x i)
374+
365375
let rec everyAux arr i b len =
366376
if i = len then true
367377
else if b (getUnsafe arr i) [@bs] then

jscomp/others/belt_Array.mli

+13
Original file line numberDiff line numberDiff line change
@@ -488,6 +488,19 @@ val reduceReverse2:
488488
]}
489489
*)
490490

491+
val reduceWithIndexU: 'a array -> 'b -> ('b -> 'a -> int -> 'b [@bs]) -> 'b
492+
val reduceWithIndex: 'a array -> 'b -> ('b -> 'a -> int -> 'b) -> 'b
493+
(** [reduceWithIndex xs f]
494+
495+
Applies [f] to each element of [xs] from beginning to end. Function [f] has three parameters: the item
496+
from the array and an “accumulator”, which starts with a value of [init] and the index of each element. [reduceWithIndex]
497+
returns the final value of the accumulator.
498+
499+
@example {[
500+
reduceWithIndex [|1;2;3;4|] 0 (fun acc x i -> acc + x + i) = 16;
501+
]}
502+
*)
503+
491504
val someU: 'a array -> ('a -> bool [@bs]) -> bool
492505
val some: 'a array -> ('a -> bool) -> bool
493506
(** [some xs p]

jscomp/test/bs_array_test.ml

+1
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ let () =
9999
eq __LOC__ (A.reduceReverse [||] 100 (-)) 100;
100100
eq __LOC__ (A.reduceReverse [|1;2|] 100 (-)) 97;
101101
eq __LOC__ (A.reduceReverse [|1;2;3;4|] 100 (-) ) 90;
102+
eq __LOC__ (A.reduceWithIndex [|1;2;3;4|] 0 (fun acc x i -> acc + x + i) = 16);
102103
b __LOC__
103104
(A.reduceReverse2 [|1;2;3|] [|1;2|] 0 (fun acc x y -> acc + x + y) = 6)
104105
let addone = fun [@bs] x -> x + 1

0 commit comments

Comments
 (0)