Skip to content

Commit

Permalink
Merge pull request jashkenas#1700 from megawac/compose
Browse files Browse the repository at this point in the history
Breaking: Optimization for compose
  • Loading branch information
jashkenas committed Jun 24, 2014
2 parents 0ae8dc9 + bc96528 commit 673df16
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
16 changes: 16 additions & 0 deletions test/functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -478,6 +478,22 @@

composed = _.compose(greet, exclaim);
equal(composed('moe'), 'hi: moe!', 'in this case, the functions are also commutative');

// f(g(h(x, y, z)))
function h(x, y, z) {
equal(arguments.length, 3, 'First function called with multiple args');
return z * y;
};
function g(x) {
equal(arguments.length, 1, 'Composed function is called with 1 argument');
return x;
};
function f(x) {
equal(arguments.length, 1, 'Composed function is called with 1 argument');
return x * 2;
};
composed = _.compose(f, g, h);
equal(composed(1, 2, 3), 12);
});

test('after', function() {
Expand Down
11 changes: 6 additions & 5 deletions underscore.js
Original file line number Diff line number Diff line change
Expand Up @@ -804,13 +804,14 @@
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = function() {
var funcs = arguments;
var funcs = arguments, length = funcs.length;
return function() {
var args = arguments;
for (var i = funcs.length - 1; i >= 0; i--) {
args = [funcs[i].apply(this, args)];
var idx = length - 1,
result = funcs[idx].apply(this, arguments);
while (idx--) {
result = funcs[idx].call(this, result);
}
return args[0];
return result;
};
};

Expand Down

0 comments on commit 673df16

Please sign in to comment.