Skip to content

Instantly share code, notes, and snippets.

@nobitagit
Last active June 6, 2018 21:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nobitagit/99c427e5ec161e0d48263e5be5849e65 to your computer and use it in GitHub Desktop.
Save nobitagit/99c427e5ec161e0d48263e5be5849e65 to your computer and use it in GitHub Desktop.
Pipe implementation in js
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);
// 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