Skip to content

Commit 71899ac

Browse files
committed
Add Array.getBy
1 parent e11670b commit 71899ac

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

jscomp/others/belt_Array.ml

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,22 @@ let mapU a f =
265265

266266
let map a f = mapU a (fun[@bs] a -> f a)
267267

268+
let getByU a p =
269+
let l = length a in
270+
let i = ref 0 in
271+
let r = ref None in
272+
while !r == None && !i < l do
273+
let v = (getUnsafe a !i) in
274+
if p v [@bs] then
275+
begin
276+
r := Some v;
277+
end;
278+
incr i
279+
done;
280+
!r
281+
282+
let getBy a p = getByU a (fun[@bs] a -> p a)
283+
268284
let keepU a f =
269285
let l = length a in
270286
let r = makeUninitializedUnsafe l in

jscomp/others/belt_Array.mli

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,16 @@ val map: 'a array -> ('a -> 'b ) -> 'b array
369369
370370
*)
371371

372+
val getByU: 'a t -> ('a -> bool [@bs]) -> 'a option
373+
val getBy: 'a t -> ('a -> bool) -> 'a option
374+
(** [getBy xs p] returns [Some value] for the first value in [xs] that satisifies the predicate function [p]; returns [None] if no element satisifies the function.
375+
376+
@example {[
377+
getBy [|1;4;3;2|] (fun x -> x mod 2 = 0) = Some 4
378+
getBy [|15;13;11|] (fun x -> x mod 2 = 0) = None
379+
]}
380+
*)
381+
372382
val keepU: 'a array -> ('a -> bool [@bs]) -> 'a array
373383
val keep: 'a array -> ('a -> bool ) -> 'a array
374384
(** [keep xs p ]

0 commit comments

Comments
 (0)