-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRangeJS.js
More file actions
32 lines (31 loc) · 891 Bytes
/
RangeJS.js
File metadata and controls
32 lines (31 loc) · 891 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// RangeJS.js
function RangeJS(start, end, step = 1) {
if (isNaN(start) || isNaN(end) || isNaN(step)) {
throw NaN;
}
if (Math.trunc(step) === 0) {
throw new Error('step is 0');
}
if (!new.target) {
return Array.from((new RangeJS(this.start, this.end, this.step))[Symbol.iterator]());
}
this.start = Math.trunc(start);
this.step = Math.trunc(step);
this.reversed = this.step < 0;
this.end = Math.trunc(end);
}
RangeJS.prototype[Symbol.iterator] = function* () {
for (let i = this.start; i < this.end; i += this.step) {
yield i;
}
};
RangeJS.prototype[Symbol.toPrimitive] = function (hint) {
if (hint === 'string') {
return `Range(${this.start}, ${this.end}, ${this.step}),`;
}
let length = 0;
for (const argument of this[Symbol.iterator]) {
length++;
}
return length;
};