Skip to content

Commit

Permalink
fix(array): fix up A.takeWhile implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
mobily committed Dec 10, 2022
1 parent 294fc8f commit 235f223
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 10 deletions.
4 changes: 2 additions & 2 deletions __tests__/Array/dropWhile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ describe('dropWhile', () => {
})

it('drops elements from the beginning of the array until an element is reached which does not satisfy the given predicate', () => {
const result = A.dropWhile(xs, x => x < 4)
expect(result).toEqual([4, 5, 6, 7])
expect(A.dropWhile(xs, x => x < 4)).toEqual([4, 5, 6, 7])
expect(A.dropWhile([1, 3, 5, 7, 9], x => x < 5)).toEqual([5, 7, 9])
})

it('returns correct array elements if either true or false', () => {
Expand Down
4 changes: 2 additions & 2 deletions __tests__/Array/takeWhile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ const xs = [1, 2, 3, 4, 5, 6, 7]
// TODO: expectType
describe('takeWhile', () => {
it('returns a new array, filled with elements from the provided array until an element does not pass the provided predicate', () => {
const result = A.takeWhile(xs, x => x < 4)
expect(result).toEqual([1, 2, 3])
expect(A.takeWhile(xs, x => x < 4)).toEqual([1, 2, 3])
expect(A.takeWhile([3, 5, 3], x => x < 4)).toEqual([3])
})

it('returns correct array elements if either true or false', () => {
Expand Down
23 changes: 17 additions & 6 deletions src/Array/Array.res
Original file line number Diff line number Diff line change
Expand Up @@ -172,13 +172,24 @@ let takeExactly = (xs, n) =>
"Returns a new array, filled with elements from the provided array until an element doesn't pass the provided predicate."
)
@gentype
let takeWhile = (xs, predicateFn) =>
Belt.Array.reduceU(xs, [], (. acc, element) => {
if predicateFn(element) {
Js.Array2.push(acc, element)->ignore
let takeWhile = (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) {
Js.Array2.push(arr, value)->ignore
index := succ(index.contents)
} else {
break := true
}
acc
})
}

arr
}

%comment(
"Returns a new array that does not contain the first `n` elements of the provided array, or an empty array if `n` is either less than `0` or greater than the length of the provided array."
Expand Down

0 comments on commit 235f223

Please sign in to comment.