Skip to content

Instantly share code, notes, and snippets.

@devisnotnull
Created April 3, 2019 21:25
Show Gist options
  • Save devisnotnull/22d40e6720193228886b3742f1eb5580 to your computer and use it in GitHub Desktop.
Save devisnotnull/22d40e6720193228886b3742f1eb5580 to your computer and use it in GitHub Desktop.
Simple ES6 functional composition
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