This repository was archived by the owner on Feb 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinitial.ts
66 lines (59 loc) · 1.94 KB
/
initial.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import type {
Initial,
IsomorphicIterable,
ReadOnlyArray,
} from "@vangware/types";
import { getIterator } from "./getIterator.js";
import { handleIsomorphicIterable } from "./handleIsomorphicIterable.js";
import type { GeneratorOutput } from "./types/GeneratorOutput.js";
import type { ReadOnlyIterableIterator } from "./types/ReadOnlyIterableIterator.js";
/**
* Get all elements except the last one of an iterable or asynchronous iterable.
*
* @category Generators
* @example
* ```typescript
* initial([1, 2, 3]); // [1, 2]
* ```
* @param iterable Iterable to get the items from.
* @returns Iterable with all items except the last one.
*/
export const initial = handleIsomorphicIterable(
iterable =>
function* () {
const iterator = getIterator(iterable);
const item = { done: false, ...iterator.next() };
// eslint-disable-next-line functional/no-loop-statements
while (!item.done) {
const next = { done: false, ...iterator.next() };
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
next.done ? undefined : yield item.value;
// eslint-disable-next-line functional/immutable-data, functional/no-expression-statements
Object.assign(item, next);
}
},
)(
iterable =>
async function* () {
const iterator = getIterator(iterable);
const item = {
done: false,
...(await iterator.next()),
};
// eslint-disable-next-line functional/no-loop-statements
while (!item.done) {
const next = {
done: false,
...(await iterator.next()),
};
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
next.done ? undefined : yield item.value;
// eslint-disable-next-line functional/immutable-data, functional/no-expression-statements
Object.assign(item, next);
}
},
) as <Iterable extends IsomorphicIterable>(
iterable: Iterable,
) => Iterable extends ReadOnlyArray
? ReadOnlyIterableIterator<Initial<Iterable>[number]>
: GeneratorOutput<Iterable>;