-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
iterable.ts
39 lines (31 loc) · 1.09 KB
/
iterable.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
import {invariant, addHiddenFinalProp} from "./utils";
// inspired by https://github.com/leebyron/iterall/
declare var Symbol;
function iteratorSymbol() {
return (typeof Symbol === "function" && Symbol.iterator) || "@@iterator";
}
export const IS_ITERATING_MARKER = "__$$iterating";
export interface Iterator<T> {
next(): {
done: boolean;
value?: T;
};
}
export function arrayAsIterator<T>(array: T[]): T[] & Iterator<T> {
// TODO: this should be removed in the next major version of MobX
// returning an array for entries(), values() etc for maps was a mis-interpretation of the specs..
invariant(array[IS_ITERATING_MARKER] !== true, "Illegal state: cannot recycle array as iterator");
addHiddenFinalProp(array, IS_ITERATING_MARKER, true);
let idx = -1;
addHiddenFinalProp(array, "next", function next() {
idx++;
return {
done: idx >= this.length,
value: idx < this.length ? this[idx] : undefined
};
});
return array as any;
}
export function declareIterator<T>(prototType, iteratorFactory: () => Iterator<T>) {
addHiddenFinalProp(prototType, iteratorSymbol(), iteratorFactory);
}