Last active
June 6, 2018 21:20
-
-
Save nobitagit/99c427e5ec161e0d48263e5be5849e65 to your computer and use it in GitHub Desktop.
Pipe implementation in js
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
const len = num => { | |
const isNum = !isNaN(parseFloat(num)) && isFinite(num); | |
if (!isNum) { | |
return new Error('not a number'); | |
} | |
const str = num.toString().replace('.', ''); | |
return str.length; | |
} | |
const assertions = [ | |
len(4) === 1, | |
len(44) === 2, | |
len(444) === 3, | |
len(4444) === 4, | |
len(2222.11) === 6, | |
len("abc") instanceof Error, | |
]; | |
assertions.map(console.assert); |
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
// goal is to make this work | |
pipe( | |
function a(c) { | |
return c + 1; | |
}, | |
a => a + 1, | |
)(3); // 5 | |
// 1st stage, nope... | |
const pipe = (...args) => { | |
return args.map(fn => fn()) | |
} | |
// 2nd stage, not quite.. | |
const pipe = (...args) => { | |
return args.reduce((acc, fn) => { | |
const ret = fn(acc); | |
return ret; | |
}, null); | |
} | |
// 3rd stage, it works! | |
const pipe = (...args) => arg => { | |
return args.reduce((acc, fn) => { | |
const ret = fn(acc); | |
return ret; | |
}, arg); | |
} | |
// 4th stage, cleanup | |
const pipe = (...args) => arg => { | |
return args.reduce((acc, fn) => fn(acc), arg); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment