Node.js examples for Object:Class Definition
class to represent a range of numbers
const Range = function(start, end, step = 1) { this.start = start;// w ww .j a va 2s . c o m this.end = end; step > 0 ? this.step = step : this.step = -step; }; Range.prototype.size = function () { return (Math.abs(this.start - this.end) / this.step) + 1; }; Range.prototype.each = function (callback) { if (this.start > this.end) { for (let i = this.start; i >= this.end; i -= this.step) { callback(i); } } else { for (let i = this.start; i <= this.end; i += this.step) { callback(i); } } }; Range.prototype.includes = function (val) { if (this.start > this.end) { for (let i = this.start; i >= this.end; i -= this.step) { if (val === i) return true; } } else { for (let i = this.start; i <= this.end; i += this.step) { if (val === i) return true; } } return false; }; // Test ...!! // const range2 = new Range(1, 3, 2); console.log(range2); console.log('size', range2.size()); // 2 range2.each((input) => { console.log('element : ', input); }); console.log(range2.includes(3)); // true; console.log(range2.includes(0)); // false; const range3 = new Range(1, 3, -2); console.log(range3); console.log('size', range3.size()); // 2 range3.each((input) => { console.log('element : ', input); }); console.log(range3.includes(3)); // true; console.log(range3.includes(0)); // false; var range1 = new Range(100, 50, -5); var range2 = new Range(56, 43); var range3 = new Range(-5, 20); console.log(range1, range2, range3); console.log(range1.size(), range2.size(), range3.size()); console.log(range1.includes(95), range2.includes(57), range3.includes(5)); range1.each((val) => console.log(val)); range2.each((val) => console.log(val)); range3.each((val) => console.log(val));