-
Notifications
You must be signed in to change notification settings - Fork 7
/
dropLastWhile.ts
55 lines (47 loc) · 1.67 KB
/
dropLastWhile.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Copyright (c) 2020 Jozty. All rights reserved. MIT license.
import type {
InferElementType,
InferType,
PH,
Predicate1,
} from './utils/types.ts';
import { slice } from './slice.ts';
import { dispatch } from './utils/dispatch.ts';
import DropLastWhileTransformer from './utils/Transformers/dropLastWhile.ts';
import curryN from './utils/curry_n.ts';
// @types
type DropLastWhile_2<T> = <L extends T[] | string>(list: L) => InferType<L>;
type DropLastWhile_1<L extends unknown[] | string> = (
predicate: Predicate1<InferElementType<L>>,
) => InferType<L>;
type DropLastWhile =
& (<T>(predicate: Predicate1<T>) => DropLastWhile_2<T>)
& (<L extends unknown[] | string>(
predicate: PH,
list: L,
) => DropLastWhile_1<L>)
& (<T, L extends T[] | string>(
predicate: Predicate1<T>,
list: L,
) => InferType<L>);
function _dropLastWhile<L extends T[] | string, T>(
predicate: Predicate1<InferElementType<T>>,
list: L,
) {
let i = list.length - 1;
while (i >= 0 && predicate(list[i] as InferElementType<T>)) i--;
return slice(0, i + 1, list);
}
const dispatched = dispatch(DropLastWhileTransformer, _dropLastWhile);
/**
* Returns a new list excluding the trailing elements of a `list` which
* satisfies `predicate`. Skips all the elements which on applied on `predicate`
* returns `true`. The new list ends with last `false`.
*
* Acts as a transducer if a transformer is passed in place of `list`
*
* const lteThree = x => x <= 3;
* Fae.dropLastWhile(lteThree, [1, 2, 3, 4, 3, 2, 1]); //=> [1, 2, 3, 4]
* Fae.dropLastWhile(x => x !== 't' , 'dispatch'); //=> 'dispat'
*/
export const dropLastWhile: DropLastWhile = curryN(2, dispatched);