From 8a5cb6c47367b19745b84a74a8a5ba1705767222 Mon Sep 17 00:00:00 2001 From: Minsang Kim Date: Sat, 10 Feb 2024 01:07:56 +0900 Subject: [PATCH] fix: A.dropWhile behaves as what it should be --- __tests__/Array/dropWhile.test.ts | 2 ++ src/Array/Array.res | 26 +++++++++++++++++++------- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/__tests__/Array/dropWhile.test.ts b/__tests__/Array/dropWhile.test.ts index 8548131..fa7baab 100644 --- a/__tests__/Array/dropWhile.test.ts +++ b/__tests__/Array/dropWhile.test.ts @@ -3,6 +3,7 @@ import { expectType } from 'ts-expect' import { A, S, pipe } from '../..' const xs = [1, 2, 3, 4, 5, 6, 7] +const ys = [1, 2, 3, 4, 3, 2, 1] // TODO: expectType describe('dropWhile', () => { @@ -30,5 +31,6 @@ describe('dropWhile (pipe)', () => { A.dropWhile(x => x < 4), ) expect(result).toEqual([4, 5, 6, 7]) + expect(A.dropWhile(ys,x=>x<=3)).toEqual([4, 3, 2, 1]) }) }) diff --git a/src/Array/Array.res b/src/Array/Array.res index 670e05f..7830c2d 100644 --- a/src/Array/Array.res +++ b/src/Array/Array.res @@ -211,14 +211,26 @@ let dropExactly = (xs, n) => n < 0 || n > length(xs) ? None : Some(Belt.Array.sl "Drops elements from the beginning of the array until an element is reached which does not satisfy the given predicate." ) @gentype -let dropWhile = (xs, predicateFn) => - Belt.Array.reduceU(xs, [], (. acc, element) => { - if !predicateFn(element) { - Js.Array2.push(acc, element)->ignore - } - acc - }) +let dropWhile = (xs, predicateFn) => { + let index = ref(0) + let break = ref(false) + let arr = [] + while index.contents < length(xs) && !break.contents { + let value = Belt.Array.getUnsafe(xs, index.contents) + + if predicateFn(value) { + index := succ(index.contents) + } else { + break := true + } + } + while index.contents < length(xs) { + Js.Array2.push(arr, Belt.Array.getUnsafe(xs, index.contents))->ignore + index := succ(index.contents) + } + arr +} %comment( "Splits the provided array into head and tail parts (as a tuple), but only if the array is not empty." )