Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: A.dropWhile behaves as what it should be #103

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions __tests__/Array/dropWhile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down Expand Up @@ -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])
})
})
26 changes: 19 additions & 7 deletions src/Array/Array.res
Original file line number Diff line number Diff line change
Expand Up @@ -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."
)
Expand Down