Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python partial equivalent in Javascript / jQuery

What is the equivalent for Pythons functools.partial in Javascript or jQuery ?

like image 953
Zitrax Avatar asked Oct 21 '15 12:10

Zitrax


2 Answers

ES6 solution

Here is a simple solution that works for ES6. However, since javascript doesn't support named arguments, you won't be able to skip arguments when creating a partial.

const partial = (func, ...args) => (...rest) => func(...args, ...rest);

Example

const greet = (greeting, person) => `${greeting}, ${person}!`;
const greet_hello = partial(greet, "Hello");

>>> greet_hello("Universe");
"Hello, Universe!"
like image 87
David Callanan Avatar answered Sep 21 '22 03:09

David Callanan


Something like this perhaps. It is a little bit tricky as javascript doesn't have named arguments like python, but this function comes pretty close.

function partial() {
  var args = Array.prototype.slice.call(arguments);
  var fn = args.shift();
  return function() {
    var nextArgs = Array.prototype.slice.call(arguments);
    // replace null values with new arguments
    args.forEach(function(val, i) {
      if (val === null && nextArgs.length) {
        args[i] = nextArgs.shift();
      }
    });
    // if we have more supplied arguments than null values
    // then append to argument list
    if (nextArgs.length) {
      nextArgs.forEach(function(val) {
        args.push(val);
      });
    }
    return fn.apply(fn, args);
  }
}

// set null where you want to supply your own arguments
var hex2int = partial(parseInt, null, 16);
document.write('<pre>');
document.write('hex2int("ff") = ' + hex2int("ff") + '\n');
document.write('parseInt("ff", 16) = ' + parseInt("ff", 16));
document.write('</pre>');
like image 33
hampusohlsson Avatar answered Sep 22 '22 03:09

hampusohlsson