-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmod.ts
51 lines (42 loc) · 1.07 KB
/
mod.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
/*!
* Last Item <https://github.com/ultirequiem/last_item>
*
* Copyright (c) Eliaz Bobadilla.
* Released under the MIT License.
*/
/**
* @param array The array of items.
*
* @returns The Last item of the array.
*/
export function lastItem<T>(array: readonly T[]): T;
/**
* @param array The array of items.
* @param length The quantity of items to take.
*
* @returns The last N items.
*/
export function lastItem<T>(array: readonly T[], length: number): T[];
export function lastItem<T>(array: readonly T[], length = 1) {
if (!Array.isArray(array)) {
throw new TypeError("Expected an array.");
}
let index = array.length;
if (index <= 0) {
throw new RangeError("Expected an array with at least one item.");
}
if (length === 1) {
return array[index - 1];
}
if (!Number.isInteger(length)) {
throw new TypeError("Expected an integer.");
}
if (length > index) {
throw new RangeError("More items were requested than there are.");
}
const result = [];
while (length--) {
result[length] = array[--index];
}
return result;
}