Last active
February 26, 2020 18:18
-
-
Save harbirchahal/fbb546f3085a769464a2fbc400d773ce to your computer and use it in GitHub Desktop.
Implementing array functions as generators
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
const log = console.log; | |
function map(fn) { | |
return function* (arr) { | |
for (const el of arr) { | |
yield fn(el); | |
} | |
} | |
} | |
function filter(fn) { | |
return function* (arr) { | |
for (const el of arr) { | |
if (fn(el)) { | |
yield el; | |
} | |
} | |
} | |
} | |
function pipe(...args) { | |
return function (arr) { | |
let r = arr; | |
for (const fn of args) { | |
r = [...fn(r)]; | |
} | |
return r; | |
} | |
} | |
const evenSquares = pipe( | |
filter(n => n % 2 === 0), | |
map(n => n * n), | |
); | |
log(evenSquares([1, 2, 3, 4])); // [4, 16] | |
const oddCubes = pipe( | |
filter(n => n % 2 !== 0), | |
map(n => n * n * n), | |
); | |
log(oddCubes([1, 2, 3, 4])); // [1, 27] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment