-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
compact.ts
25 lines (25 loc) · 879 Bytes
/
compact.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
/**
* Removes all nullish (`null` or `undefined`) values from an iterable.
*
* Use {@linkcode https://jsr.io/@core/iterutil/doc/compress/~/compress compress} to remove values based on an iterable.
* Use {@linkcode https://jsr.io/@core/iterutil/doc/filter/~/filter filter} to remove values based on a function.
* Use {@linkcode https://jsr.io/@core/iterutil/doc/async/compact/~/compact compact} to compact iterables asynchronously.
*
* @param iterable The iterable to compact.
* @returns The compacted iterable.
*
* @example
* ```ts
* import { compact } from "@core/iterutil/compact";
*
* const iter = compact([1, undefined, 2, null, 3]);
* console.log(Array.from(iter)); // [1, 2, 3]
* ```
*/
export function* compact<T>(iterable: Iterable<T>): Iterable<NonNullable<T>> {
for (const value of iterable) {
if (value != null) {
yield value;
}
}
}