Last active
September 20, 2017 21:18
-
-
Save johnnynotsolucky/0e02a3656f1b96d8980006ae8e091097 to your computer and use it in GitHub Desktop.
Functional Utils
This file contains 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 ifElse = (condition, whenTrue, whenFalse) => { | |
return (...args) => | |
condition(...args) | |
? whenTrue(...args) | |
: whenFalse(...args) | |
} | |
const identity = x => () => x | |
const inc = x => x + 1 | |
const incIfInt = ifElse(Number.isInteger, inc, identity(NaN)) | |
incIfInt('1') // NaN | |
incIfInt(1) // 2 |
This file contains 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
// [Ramda pipe](http://ramdajs.com/docs/#pipe) | |
const sequence = (...operations) => { | |
const apply = (result, operation, index) => | |
index !== 0 | |
? operation(result) | |
: operation(...result) | |
return (...o) => operations.reduce(apply, o) | |
} | |
const negate = x => -x | |
const inc = x => x + 1 | |
sequence(Math.pow, negate, inc)(3, 4) // -(3^4) + 1 | |
// [Ramda compose](http://ramdajs.com/docs/#compose) | |
const compose = (...operations) => sequence(...operations.reverse()) | |
const sum = x => y => x + y | |
const multiply = (x, y) => x * y | |
compose(Math.abs, sum(1), multiply)(2, -4) // 7 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment