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