-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
last.ts
26 lines (26 loc) · 951 Bytes
/
last.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
/**
* Returns the last element of an iterable.
*
* Use {@linkcode https://jsr.io/@core/iterutil/doc/first/~/first first} to get the first element.
* Use {@linkcode https://jsr.io/@core/iterutil/doc/nth/~/nth nth} to get the n-th element.
* Use {@linkcode https://jsr.io/@core/iterutil/doc/find/~/find find} to find an element.
* Use {@linkcode https://jsr.io/@core/iterutil/doc/async/last/~/last last} to get the last element asynchronously.
*
* @param iterable The iterable to get the last element of.
* @returns The last element of the iterable, or `undefined` if the iterable is empty.
*
* @example
* ```ts
* import { last } from "@core/iterutil/last";
*
* console.log(last([1, 2, 3])); // 3
* console.log(last([])); // undefined
* ```
*/
export function last<T>(iterable: Iterable<T>): T | undefined {
let lastValue: T | undefined = undefined;
for (const value of iterable) {
lastValue = value;
}
return lastValue;
}