-
Notifications
You must be signed in to change notification settings - Fork 0
/
dropRightWhile.ts
39 lines (30 loc) · 907 Bytes
/
dropRightWhile.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// solution 1.
function dropRightWhile<T>(array: T[], predicate: (value: T) => boolean) {
let index = array.length - 1
while (index >= 0 && predicate(array[index])) {
--index
}
return array.slice(0, index + 1)
}
// solution 2.
function dropRightWhileWithForLoop<T>(array: T[], predicate: (value: T) => boolean) {
for (let i = array.length - 1; i >= 0; --i) {
if (!predicate(array[i])) {
return array.slice(0, i + 1)
}
}
return []
}
// solution 3.
function dropRightWhileWithForLoopAndSingleReturn<T>(array: T[], predicate: (value: T) => boolean) {
const rev = array.slice().reverse()
let droppedIndex = array.length - 1
for (const element of rev) {
if (!predicate(element)) {
break
}
--droppedIndex
}
return array.slice(0, droppedIndex + 1)
}
export { dropRightWhile, dropRightWhileWithForLoop, dropRightWhileWithForLoopAndSingleReturn }