const test=require("node:test");
const assert=require("assert");
class Fib {
constructor(limit) {
this.limit=limit;
this.count=0;
this.val=0;
this.next_val=1;
}
[Symbol.iterator]() {
return new FibIterator(this);
}
}
class FibIterator {
constructor(fib) {
this.fib=fib;
}
next() {
if (this.fib.count <= this.fib.limit) {
let tmp = this.fib.val;
this.fib.val = this.fib.next_val;
this.fib.next_val = tmp+this.fib.next_val;
this.fib.count++;
return {done:false, value:tmp};
} else {
return {done:true};
}
}
}
test("Fib(6)", (t)=> {
let results = [];
for (let f of new Fib(6)) { results.push(f); }
assert.deepStrictEqual(results,[0,1,1,2,3,5,8]);
});
test("Fib(42)", (t)=> {
let result = -1;
for (let f of new Fib(42)) { result = f; }
assert.strictEqual(result,267914296);
});
test("Fib(2) destructure", (t)=> {
let [a,b,c] = new Fib(6);
assert.deepStrictEqual([a,b,c],[0,1,1]);
});
test("Fib(6) spread", (t)=> {
assert.deepStrictEqual([...new Fib(6)], [0,1,1,2,3,5,8]);
});