Skip to content

Instantly share code, notes, and snippets.

@harbirchahal
Last active February 26, 2020 18:18
Show Gist options
  • Save harbirchahal/fbb546f3085a769464a2fbc400d773ce to your computer and use it in GitHub Desktop.
Save harbirchahal/fbb546f3085a769464a2fbc400d773ce to your computer and use it in GitHub Desktop.
Implementing array functions as generators
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