Last active
March 5, 2019 07:19
-
-
Save ervinne13/a59ab06259af8130231be7923106c548 to your computer and use it in GitHub Desktop.
Composing functions by piping
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 { 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' } | |
*/ |
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 pipe = (...fns) => { | |
return param => fns.reduce( | |
(result, fn) => fn(result), | |
param | |
) | |
} | |
module.exports = pipe; |
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
// 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