-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
35 lines (35 loc) · 975 Bytes
/
index.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
/**
* Takes an integer value and returns the item at that index, allowing for
* positive and negative integers. Negative integers count back from the last
* item in the array-like.
*
* @param array The array-like to search.
* @param index The index of the item to return.
* @returns The item at the given index.
*
* @example
* #### Basic usage
* ```ts
* at(["a", "b"], 0) // "a"
* at(["a", "b"], 1) // "b"
* at(["a", "b"], 9) // undefined
* at(["a", "b"], -1) // "b"
* at(["a", "b"], -2) // "a"
* at(["a", "b"], -9) // undefined
*
* at("bar", 2) // "r"
* at("bar", -1) // "r"
*
* at(null, 0) // undefined
* at(undefined, 1) // undefined
* ```
* @category Array
*/
export const at = <T extends ArrayLike<unknown>>(
array: T | null | undefined,
index: number
): T[number] | undefined => {
if (!array) { return undefined }
if (index < 0) { index += array.length }
return (index < 0 || index >= array.length) ? undefined : array[index]
}