Add helpers for partial application

This commit is contained in:
Andrew Stewart 2015-02-23 14:31:52 -08:00
parent 372c384b11
commit 2eaea42a72
2 changed files with 38 additions and 3 deletions

View File

@ -1,6 +1,5 @@
// A collection of useful helper functions, used internally but not exported
// with the rest of Cylon.
"use strict";
var __slice = Array.prototype.slice;
@ -151,6 +150,24 @@ function arity(fn, n) {
};
}
function partial(fn) {
var args = __slice.call(arguments, 1);
return function() {
return fn.apply(null, args.concat(__slice.call(arguments)));
};
}
function partialRight(fn) {
var args = __slice.call(arguments, 1);
return function() {
return fn.apply(null, __slice.call(arguments).concat(args));
};
}
extend(H, {
arity: arity
arity: arity,
partial: partial,
partialRight: partialRight
});

View File

@ -220,4 +220,22 @@ describe("Helpers", function() {
expect(fn).to.be.calledWith("one");
});
});
describe("#partial", function() {
it("partially applies a function's arguments", function() {
var fn = spy();
var one = _.partial(fn, "one", "two");
one("three");
expect(fn).to.be.calledWith("one", "two", "three");
});
});
describe("#partialRight", function() {
it("partially applies arguments to the end of a fn call", function() {
var fn = spy();
var one = _.partialRight(fn, "two", "three");
one("one");
expect(fn).to.be.calledWith("one", "two", "three");
});
});
});