Skip to content

Instantly share code, notes, and snippets.

@ervinne13
Last active March 5, 2019 07:19
Show Gist options
  • Save ervinne13/a59ab06259af8130231be7923106c548 to your computer and use it in GitHub Desktop.
Save ervinne13/a59ab06259af8130231be7923106c548 to your computer and use it in GitHub Desktop.
Composing functions by piping
const { validate, normalize, persist } = require('./user-module')
const pipe = require('./pipe')
const saveUser = (user) => {
return pipe(
validate,
normalize,
persist
)(user)
}
const savedUser = saveUser({
firstName: 'ervinne',
lastName: 'sodusta',
})
console.log('user saved', savedUser)
/*
Prints out:
validating { firstName: 'ervinne', lastName: 'sodusta' }
normalizing { firstName: 'ervinne', lastName: 'sodusta' }
persisting { firstName: 'ervinne', lastName: 'sodusta' }
user saved { firstName: 'ervinne', lastName: 'sodusta' }
*/
const pipe = (...fns) => {
return param => fns.reduce(
(result, fn) => fn(result),
param
)
}
module.exports = pipe;
// Note: these are samples only, but if there are real functions here that does mutations, create a new object/clone instead
const UserModule = {
validate: (user) => {
console.log('validating', user)
// ...
return user;
},
normalize: (user) => {
console.log('normalizing', user)
// ...
return user;
},
persist: (user) => {
console.log('persisting', user)
// ...
return user;
},
}
module.exports = UserModule;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment