Created
April 3, 2019 21:25
-
-
Save devisnotnull/22d40e6720193228886b3742f1eb5580 to your computer and use it in GitHub Desktop.
Simple ES6 functional composition
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 compose = (...fns) => | |
fns.reduce((prevFn, nextFn) => | |
(...args) => nextFn(prevFn(...args)), | |
value => value | |
); | |
const compose2 = (fn, g) => | |
(...args) => | |
fn(g(...args)) | |
const pipe = (...fns) => | |
fns.reduce(compose2); | |
const userValue = { | |
'name': 'Main name', | |
'title': 'Main title', | |
'projects': [ | |
{ | |
'title': 'title', | |
'name': 'description' | |
} | |
] | |
} | |
const getProjects = user => user.projects | |
const getFirstProjects = projects => (Array.isArray(projects) && projects.length > 0) ? projects[0] : [] | |
const getProjectTitle = project => project.title | |
// Functional composition | |
const fetchProjectName = compose( | |
getProjects, | |
getFirstProjects, | |
getProjectTitle | |
)(userValue) | |
module.exports = { | |
compose, | |
compose2, | |
pipe | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment