Skip to content

Instantly share code, notes, and snippets.

@johnnynotsolucky
Last active September 20, 2017 21:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnnynotsolucky/0e02a3656f1b96d8980006ae8e091097 to your computer and use it in GitHub Desktop.
Save johnnynotsolucky/0e02a3656f1b96d8980006ae8e091097 to your computer and use it in GitHub Desktop.
Functional Utils
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
// [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