From 2eaea42a726937b958850db0b3d184be9b0abcb2 Mon Sep 17 00:00:00 2001 From: Andrew Stewart Date: Mon, 23 Feb 2015 14:31:52 -0800 Subject: [PATCH] Add helpers for partial application --- lib/utils/helpers.js | 23 ++++++++++++++++++++--- spec/lib/utils/helpers.spec.js | 18 ++++++++++++++++++ 2 files changed, 38 insertions(+), 3 deletions(-) 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"); + }); + }); });