This JavaScript code defines a CollatzConjecture class that implements the iterable protocol to generate a sequence according to the Collatz conjecture rules starting from a given number. When instantiated with a start number and iterated over, it produces a series of numbers according to the conjecture, which ends when the series reaches the number 1. It demonstrates usage by creating a series starting from 13 and logging it to the console.
class CollatzConjecture implements Iterable<number> {
private next = this.startFrom;
constructor(private startFrom: number) {}
*[Symbol.iterator](): Generator<number> {
while (this.next !== 1) {
this.next = this.next % 2 === 0 ? this.next / 2 : this.next * 3 + 1;
yield this.next;
}
}
}
const series = [...new CollatzConjecture(13)];
console.log(series);