diff --git a/lib/utils/helpers.js b/lib/utils/helpers.js index 4e80378..e442922 100644 --- a/lib/utils/helpers.js +++ b/lib/utils/helpers.js @@ -1,6 +1,5 @@ // A collection of useful helper functions, used internally but not exported -// with the rest of Cylon. - +// 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 }); diff --git a/spec/lib/utils/helpers.spec.js b/spec/lib/utils/helpers.spec.js index 45843ab..afa26d8 100644 --- a/spec/lib/utils/helpers.spec.js +++ b/spec/lib/utils/helpers.spec.js @@ -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"); + }); + }); });