Skip to content

Instantly share code, notes, and snippets.

@marcoslhc
Created April 9, 2017 01:12
Show Gist options
  • Select an option

  • Save marcoslhc/6d439a2747f554c8c82c91a615ec307d to your computer and use it in GitHub Desktop.

Select an option

Save marcoslhc/6d439a2747f554c8c82c91a615ec307d to your computer and use it in GitHub Desktop.
Iterator
range = (start, end, step = 1) => {
return {
*[Symbol.iterator]() {
let by = start >= end && step > 0 ? step*(-1) : step;
let current = start;
while ((start < end && current < end) || (start > end && current > end)) {
yield current;
current = current + by;
}
return end;
},
map(fn) {
let result = [];
for (let d of range(start, end)) {
result.push(fn(d));
}
return result;
},
reduce(fn) {
let init = start;
for(let d of range(start, end)) {
init = fn(init, d);
}
return init;
}
}
}
for (i of range(100, 0, 10)) console.log(i); // 100 90 80 70 60 50 40 30 20 10
const powerOfTwo = (x) => Math.pow(2, x)
range(0, 8).map(powerOfTwo) // [1, 2, 4, 8, 16, 32, 64, 128]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment