Search code examples
javascriptfunctional-programming

How can I pre-set arguments in JavaScript function call? (Partial Function Application)


I am trying to write a JavaScript function that will return its first argument(function) with all the rest of its arguments as preset parameters to that function.

So:

function out(a, b) {
    document.write(a + " " + b);
}

function setter(...) {...}

setter(out, "hello")("world");
setter(out, "hello", "world")();

Would output "hello world" twice. for some implementation of setter

I ran into an issue with manipulating the arguments array on my first try, but it seems there would be a better way to do this.


Solution

  • First of all, you need a partial - there is a difference between a partial and a curry - and here is all you need, without a framework:

    function partial(func /*, 0..n args */) {
      var args = Array.prototype.slice.call(arguments, 1);
      return function() {
        var allArguments = args.concat(Array.prototype.slice.call(arguments));
        return func.apply(this, allArguments);
      };
    }
    

    Now, using your example, you can do exactly what you are after:

    partial(out, "hello")("world");
    partial(out, "hello", "world")();
    
    // and here is my own extended example
    var sayHelloTo = partial(out, "Hello");
    sayHelloTo("World");
    sayHelloTo("Alex");
    

    The partial() function could be used to implement, but is not currying. Here is a quote from a blog post on the difference:

    Where partial application takes a function and from it builds a function which takes fewer arguments, currying builds functions which take multiple arguments by composition of functions which each take a single argument.