Created
June 22, 2021 11:31
-
-
Save harbirchahal/9bbb285881570e957eb114f7bea3489f to your computer and use it in GitHub Desktop.
Composable array functions that avoid intermediate creation of resultant array.
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
/* | |
Ref: https://monet.github.io/monet.js/ | |
*/ | |
const { Some, None } = Monet; | |
function map(fn) { | |
return function (v) { | |
return Some(fn(v)); | |
} | |
} | |
function filter(fn) { | |
return function (v) { | |
const r = fn(v); | |
return r ? Some(v) : None(); | |
} | |
} | |
function pipe(...fns) { | |
return function (arr) { | |
const result = []; | |
for (const e of arr) { | |
let m = Some(e); | |
for (const fn of fns) { | |
m = m.flatMap(fn); | |
if (m.isNone()) { | |
break; | |
} | |
} | |
if (m.isSome()) { | |
m.forEach(v => result.push(v)); | |
} | |
} | |
return result; | |
} | |
} | |
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