Create a gist now

Instantly share code, notes, and snippets.

@mbjordan /note.md
Last active Dec 9, 2015

What would you like to do?
Very simple JavaScript partial and partialRight functions

Using Array.slice can be bad news!

Instead, a simple function to convert the arguments object to an Array can be used:

function argumentsToArray(args, pointer) {
    var arr = new Array(args.length);
    for (var idx = 0; idx < arr.length; idx++) {
        if (!!pointer && (pointer - 1) === idx) continue;
        arr[idx] = args[idx];
    }
    return arr;
}

Then...

function partial(fn) {
    var args_a = argumentsToArray(arguments, 1);
    return function partialApplicator() {
        var args_b = argumentsToArray(arguments);
        return fn.apply(undefined, args_a.concat(args_b));
    };
}
function partial(fn) {
var args_a = Array.prototype.slice.call(arguments, 1);
return function partialApplicator() {
var args_b = Array.prototype.slice.call(arguments);
return fn.apply(undefined, args_a.concat(args_b));
};
}
// For use on partialRight, see http://ramdajs.com/0.17/docs/#partialRight
function partialRight(fn) {
var args_a = Array.prototype.slice.call(arguments, 1);
return function partialApplicator() {
var args_b = Array.prototype.slice.call(arguments);
// Just change the order of concatenation
return fn.apply(undefined, args_b.concat(args_a));
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment