Skip to content

Commit 0894b8c

Browse files
committed
feat(iterator from): Adding returns for Iterator and object with random next
1 parent 360eed4 commit 0894b8c

File tree

1 file changed

+22
-6
lines changed
  • workspaces/adventure-pack/goodies/typescript/Iterator.from

1 file changed

+22
-6
lines changed

workspaces/adventure-pack/goodies/typescript/Iterator.from/index.ts

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,30 @@ declare global {
1111
): IterableIterator<TElem>;
1212
}
1313
}
14+
1415
(globalThis as Record<string, unknown>).Iterator ??= {};
1516

1617
(
1718
(globalThis as Record<string, unknown>).Iterator as Record<string, unknown>
18-
).from ??= function <T>(iterator: unknown): Iterable<T> {
19-
return (iterator as Iterator<T>).toIterable();
19+
).from ??= function <T>(
20+
object: Iterator<T> | Iterable<T> | { next(): IteratorResult<T> },
21+
): IterableIterator<T> {
22+
if (Symbol.iterator in object) {
23+
return object as IterableIterator<T>;
24+
} else if (
25+
"toIterable" in object &&
26+
typeof (object as Iterator<T>).toIterable === "function"
27+
) {
28+
return (object as Iterator<T>).toIterable();
29+
} else {
30+
return (function* () {
31+
let result: IteratorResult<T>;
32+
do {
33+
result = object.next();
34+
if (!result.done) {
35+
yield result.value;
36+
}
37+
} while (!result.done);
38+
})();
39+
}
2040
};
21-
22-
Iterator.from([1, 2, 3]);
23-
Iterator.from("hello world");
24-
Iterator.from(new Set([1, 1, 2, 3, 3]));

0 commit comments

Comments
 (0)