Created
September 26, 2017 22:30
-
-
Save oliverjam/27b11864460abe6bc9d5d0937c43de4d to your computer and use it in GitHub Desktop.
Simple pipe created by oliverjam - https://repl.it/Lfew/3
This file contains hidden or 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
// pipe takes an arbitrary number of functions as arguments | |
// It returns a new function waiting for a value to be passed in | |
function pipe(...fns) { | |
return function(val) { | |
let finalResult; | |
for (fn of fns) { | |
// Call each function in turn with val (the first time) or the previous result | |
finalResult = fn(finalResult || val); | |
} | |
return finalResult; | |
} | |
} | |
// This can be simplified a lot with arrow functions and reduce | |
const arrowPipe = (...fns) => val => fns.reduce((prev, fn) => fn(prev), val); | |
const capitalise = str => str[0].toUpperCase() + str.slice(1); | |
// appendChar takes a character to append and then | |
// returns a function waiting for a string to append the character to | |
const appendChar = char => x => x + char; | |
// We can preload it with an exclamation mark | |
const exclaim = appendChar('!'); | |
// Preload pipe with the functions we want to be called | |
// This returns a new function waiting for a value | |
const formatString = pipe( | |
capitalise, | |
exclaim | |
); | |
// We can call this function as normal | |
formatString('hi'); // 'Hi!' | |
// Alternatively this could all be done in one go | |
pipe( | |
capitalise, | |
appendChar('!') | |
)('hi'); // Also 'Hi!' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment