Skip to content

Instantly share code, notes, and snippets.

@Floofies
Last active September 10, 2018 23:08
Show Gist options
  • Save Floofies/6658de4e3bb2c1302d8265a000b0f97c to your computer and use it in GitHub Desktop.
Save Floofies/6658de4e3bb2c1302d8265a000b0f97c to your computer and use it in GitHub Desktop.
Unrolled Argument Applier
function apply(functor, thisArg = null, argsArray = null) {
if (argsArray !== null && argsArray.length > 8) {
// More than 8 arguments, use apply
return functor.apply(thisArg, argsArray);
}
if (thisArg === null) {
// thisArg is not present:
// 0 arguments, call directly
if (argsArray === null || argsArray.length === 0) return functor();
// 8 or less arguments, call with directApplier
return directAppliers[argsArray.length - 1](functor, argsArray);
}
// thisArg is present:
// 0 arguments, call with call
if (argsArray === null) return functor.call(thisArg);
// 8 or less arguments, call with callApplier
return callAppliers[argsArray.length - 1](functor, thisArg, argsArray);
}
const directAppliers = [
(functor, args) => functor(args[0]),
(functor, args) => functor(args[0], args[1]),
(functor, args) => functor(args[0], args[1], args[2]),
(functor, args) => functor(args[0], args[1], args[2], args[3]),
(functor, args) => functor(args[0], args[1], args[2], args[3], args[4]),
(functor, args) => functor(args[0], args[1], args[2], args[3], args[4], args[5]),
(functor, args) => functor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]),
(functor, args) => functor(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7])
];
const callAppliers = [
(functor, thisArg, args) => functor.call(thisArg, args[0]),
(functor, thisArg, args) => functor.call(thisArg, args[0], args[1]),
(functor, thisArg, args) => functor.call(thisArg, args[0], args[1], args[2]),
(functor, thisArg, args) => functor.call(thisArg, args[0], args[1], args[2], args[3]),
(functor, thisArg, args) => functor.call(thisArg, args[0], args[1], args[2], args[3], args[4]),
(functor, thisArg, args) => functor.call(thisArg, args[0], args[1], args[2], args[3], args[4], args[5]),
(functor, thisArg, args) => functor.call(thisArg, args[0], args[1], args[2], args[3], args[4], args[5], args[6]),
(functor, thisArg, args) => functor.call(thisArg, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7])
];
function tester() {
function test(arg1, arg2) {
"use strict";
return arg1 + arg2;
}
apply(test, null, null);
apply(test, null, ["test1", "test2"]);
apply(test, { test: 123 }, null);
apply(test, { test: 123 }, ["test1", "test2"]);
apply(test, null, ["test1", "test2", "test3", "test4", "test5", "test6", "test7", "test8"]);
apply(test, null, ["test1", "test2", "test3", "test4", "test5", "test6", "test7", "test8", "test9", "test10"]);
}
tester();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment