Created
April 9, 2017 01:12
-
-
Save marcoslhc/6d439a2747f554c8c82c91a615ec307d to your computer and use it in GitHub Desktop.
Iterator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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