What is the equivalent for Pythons functools.partial in Javascript or jQuery ?
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!"
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>');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With