-
Notifications
You must be signed in to change notification settings - Fork 7
/
nth.ts
48 lines (40 loc) · 1.48 KB
/
nth.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
// Copyright (c) 2020 Jozty. All rights reserved. MIT license.
import type { FunctorWithArLk, PH } from './utils/types.ts';
import { isArrayLike, isIterable, isIterator, isString } from './utils/is.ts';
import { getIterable } from './utils/get.ts';
import { throwFunctorError } from './utils/throw.ts';
import type { InferElementType } from './utils/types.ts';
import curryN from './utils/curry_n.ts';
// @types
type Nth_2 = <F extends FunctorWithArLk | string>(
functor: F,
) => InferElementType<F>;
type Nth_1<F extends FunctorWithArLk | string> = (
index: number,
) => InferElementType<F>;
type Nth =
& ((index: number) => Nth_2)
& (<F extends FunctorWithArLk | string>(index: PH, functor: F) => Nth_1<F>)
& (<F extends FunctorWithArLk | string>(
index: number,
functor: F,
) => InferElementType<F>);
function _nth<F extends FunctorWithArLk<T> | string, T>(
index: number,
functor: F,
) {
let f: ArrayLike<T> | string = '';
if (isArrayLike(functor)) f = functor;
else if (isIterable(functor)) f = [...functor] as T[];
else if (isIterator(functor)) f = [...getIterable(functor)] as T[];
else if (isString(functor)) f = functor;
else throwFunctorError();
index = index < 0 ? index + f.length : index;
return f[index] ? f[index] : isString(functor) ? '' : f[index];
}
/**
* Returns `index`th element of `functor`.
* Returns element counting from right end if `index` is -ve.
* Works in array-like/string/iterable/iterator
*/
export const nth = curryN(2, _nth) as Nth;