Skip to content

Instantly share code, notes, and snippets.

@radekstepan
Last active March 29, 2016 02:29
Show Gist options
  • Save radekstepan/97370ec34d01cd43e24a to your computer and use it in GitHub Desktop.
Save radekstepan/97370ec34d01cd43e24a to your computer and use it in GitHub Desktop.
Implement a function `pipe()` that takes several functions as arguments and returns a new function that will pass its argument to the first function, then pass the result to the second, then pass the result of the second to the third, and so on, finally returning the output of the last function. In other words, calling `pipe(foo, bar, baz)(1, 2,…
/node_modules
*.log
.DS_Store
language: node_js

#rangle-pipe

Implement a function pipe() that takes several functions as arguments and returns a new function that will pass its argument to the first function, then pass the result to the second, then pass the result of the second to the third, and so on, finally returning the output of the last function. In other words, calling pipe(foo, bar, baz)(1, 2, 3) would be equivalent to calling baz(bar(foo(1,2,3))).

$ nvm use
$ npm install
$ npm test
"use strict";
module.exports = function() {
let fns = arguments;
return function() {
let out = arguments;
for (let fn of fns) {
if (typeof fn != 'function') throw 'pipe() accepts only functions as arguments';
out = [ fn.apply(null, out) ];
}
return out[0];
};
};
{
"name": "rangle-pipe",
"version": "1.0.0",
"author": "Radek Stepan <[email protected]>",
"main": "index.js",
"devDependencies": {
"chai": "^3.5.0",
"mocha": "^2.4.5"
},
"scripts": {
"test": "./node_modules/.bin/mocha test.js --ui exports --bail --reporter spec"
}
}
"use strict";
let assert = require('chai').assert;
let lib = require('./index.js');
exports.foobarbaz = (done) => {
let foo = (x) => x + 'foo';
let bar = (x) => x + 'bar';
let baz = (x) => x + 'baz';
assert.deepEqual('foobarbaz', lib(foo, bar, baz)(''));
done();
};
exports.pass = (done) => {
let foo = (a, b, c) => a + b + c;
let bar = (x) => x + 2;
let baz = (x) => x + 3;
assert.deepEqual(baz(bar(foo(1, 2, 3))), lib(foo, bar, baz)(1, 2, 3));
done();
};
exports.undefined = (done) => {
let foo = (x) => x;
assert.isUndefined(lib(foo, foo, foo)());
done();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment