Number range syntax
class RangeIterator extends Iterator {
#cur;
#end;
#dir;
static {
Object.defineProperties(RangeIterator.prototype, {
[Symbol.toStringTag]: {
value: "Range Iterator",
writable: false,
enumerable: false,
configurable: true,
},
});
}
constructor(start, end) {
super();
this.#cur = typeof start === "bigint" ? start : Number(start);
this.#end = typeof end === "bigint" ? end : Number(end);
this.#dir =
typeof start === "bigint"
? start > end
? -1n
: 1n
: start > end
? -1
: 1;
}
next() {
if (
(this.#dir > 0 && this.#cur >= this.#end) ||
(this.#dir < 0 && this.#cur <= this.#end)
) {
return { done: true, value: undefined };
}
const value = this.#cur;
this.#cur += this.#dir;
return { done: false, value };
}
}
Object.setPrototypeOf(
Number.prototype,
new Proxy(Object.prototype, {
get(t, p, r) {
if (typeof p === "string") {
const np = Number(p);
if (!Number.isNaN(np)) {
const n = Number(r);
if (Number.isFinite(n)) {
return new RangeIterator(n, np);
}
}
}
return Reflect.get(t, p, r);
},
}),
);
Object.setPrototypeOf(
BigInt.prototype,
new Proxy(Object.prototype, {
get(t, p, r) {
if (typeof p === "string") {
try {
const np = BigInt(p);
const n = BigInt(r);
return new RangeIterator(n, np);
} catch {}
}
return Reflect.get(t, p, r);
},
}),
);
jsUsage:
console.log([...(10)[-3]]);
console.log([...1n[5n]]);
js