Skip to content

Commit 673df16

Browse files
committed
Merge pull request #1700 from megawac/compose
Breaking: Optimization for compose
2 parents 0ae8dc9 + bc96528 commit 673df16

File tree

2 files changed

+22
-5
lines changed

2 files changed

+22
-5
lines changed

test/functions.js

+16
Original file line numberDiff line numberDiff line change
@@ -478,6 +478,22 @@
478478

479479
composed = _.compose(greet, exclaim);
480480
equal(composed('moe'), 'hi: moe!', 'in this case, the functions are also commutative');
481+
482+
// f(g(h(x, y, z)))
483+
function h(x, y, z) {
484+
equal(arguments.length, 3, 'First function called with multiple args');
485+
return z * y;
486+
};
487+
function g(x) {
488+
equal(arguments.length, 1, 'Composed function is called with 1 argument');
489+
return x;
490+
};
491+
function f(x) {
492+
equal(arguments.length, 1, 'Composed function is called with 1 argument');
493+
return x * 2;
494+
};
495+
composed = _.compose(f, g, h);
496+
equal(composed(1, 2, 3), 12);
481497
});
482498

483499
test('after', function() {

underscore.js

+6-5
Original file line numberDiff line numberDiff line change
@@ -804,13 +804,14 @@
804804
// Returns a function that is the composition of a list of functions, each
805805
// consuming the return value of the function that follows.
806806
_.compose = function() {
807-
var funcs = arguments;
807+
var funcs = arguments, length = funcs.length;
808808
return function() {
809-
var args = arguments;
810-
for (var i = funcs.length - 1; i >= 0; i--) {
811-
args = [funcs[i].apply(this, args)];
809+
var idx = length - 1,
810+
result = funcs[idx].apply(this, arguments);
811+
while (idx--) {
812+
result = funcs[idx].call(this, result);
812813
}
813-
return args[0];
814+
return result;
814815
};
815816
};
816817

0 commit comments

Comments
 (0)