Last active
February 4, 2018 10:56
-
-
Save OttlikG/98a669a0afb63bc035d44eb90a61d4a1 to your computer and use it in GitHub Desktop.
Functional programming
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
export const compose = (...fn) => fn.reduce((f, g) => (...arg) => f(g(...arg))); |
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
export const curry = fn => { | |
const arity = fn.length; | |
return (...args) => { | |
const firstArgs = args.length; | |
if (firstArgs >= arity) { | |
return fn(...args); | |
} | |
return (...secondArgs) => { | |
return fn(...[...args, ...secondArgs]); | |
}; | |
}; | |
}; |
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
// Function composition OR | |
// import pipe from 'lodash/fp/flow'; | |
const pipe = (...fns) => x => fns.reduce((y, f) => f(y), x); | |
// Functions to compose | |
const g = n => n + 1; | |
const f = n => n * 2; | |
// Imperative composition | |
const doStuffBadly = x => { | |
const afterG = g(x); | |
const afterF = f(afterG); | |
return afterF; | |
}; | |
// Declarative composition | |
const doStuffBetter = pipe(g, f); | |
console.log( | |
doStuffBadly(20), // 42 | |
doStuffBetter(20) // 42 | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment