Range Over Iterators in TypeScript
// TypeScript doesn't have built-in support for iterators like Go 1.23,
// but we can implement similar functionality using generators.
// Let's look at the `List` type from the previous example again.
class List<T> {
private head: Element<T> | null = null;
private tail: Element<T> | null = null;
push(v: T): void {
if (this.tail === null) {
this.head = new Element(v);
this.tail = this.head;
} else {
this.tail.next = new Element(v);
this.tail = this.tail.next;
}
}
// All returns a generator function, which is TypeScript's equivalent
// of Go's iterator.
*all(): Generator<T> {
let e = this.head;
while (e !== null) {
yield e.val;
e = e.next;
}
}
}
class Element<T> {
next: Element<T> | null = null;
constructor(public val: T) {}
}
// Iteration doesn't require an underlying data structure,
// and doesn't even have to be finite! Here's a generator function
// for Fibonacci numbers.
function* genFib(): Generator<number> {
let a = 1, b = 1;
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
// Main function to demonstrate the usage
function main() {
const lst = new List<number>();
lst.push(10);
lst.push(13);
lst.push(23);
// We can use the generator in a for...of loop
for (const e of lst.all()) {
console.log(e);
}
// TypeScript doesn't have a built-in equivalent to Go's slices.Collect,
// but we can easily create our own
const all = Array.from(lst.all());
console.log("all:", all);
// Using the Fibonacci generator
for (const n of genFib()) {
if (n >= 10) {
break;
}
console.log(n);
}
}
main();
This TypeScript code implements similar functionality to the Go example. Here are some key points:
Instead of Go’s iterators, we use TypeScript’s generators, which provide similar functionality.
The
List
class is implemented with apush
method and anall
generator method that yields all elements.The
genFib
function is a generator that produces Fibonacci numbers indefinitely.In the
main
function, we demonstrate how to use these generators infor...of
loops, which is similar to Go’s range loops over iterators.TypeScript doesn’t have a direct equivalent to Go’s
slices.Collect
, but we can useArray.from()
to achieve the same result.The example maintains the structure and explanation of the original, adapted for TypeScript’s syntax and features.
This code demonstrates how to implement and use generator-based iterations in TypeScript, providing functionality similar to Go’s new iterator feature.