Last active
January 2, 2022 00:15
-
-
Save DavidWells/39c0a864dfc4a29284c7dd0f76644817 to your computer and use it in GitHub Desktop.
Automagically append arguments to function calls or add to `this` within function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Append arguments to functions */ | |
function appendArguments(fn, append, context) { | |
if (!append) return fn | |
// console.log('context', context) | |
return function () { | |
/* Original args */ | |
const args = Array.prototype.slice.call(arguments) | |
// console.log('original args', arguments) | |
/* Create clone of args */ | |
let newArgs = new Array(fn.length) | |
for (let i = 0; i < args.length; i++) { | |
newArgs[i] = args[i] | |
} | |
/* Append new arg to end */ | |
newArgs[newArgs.length] = append | |
// console.log('newArgs', newArgs) | |
return fn.apply(context, newArgs) | |
} | |
} | |
function getLastArg(args) { | |
return args[args.length - 1] | |
} | |
function normalFunction(a, b) { | |
console.log('Function this', this) | |
console.log('Function arguments', arguments) | |
console.log('Function arg a', a) | |
console.log('Function arg b', b) | |
const lastArg = getLastArg(arguments) | |
// const lastArg = arguments[arguments.length - 1] | |
console.log('Function lastArg', lastArg) | |
} | |
var arrowFunction = (a, b, ...args) => { | |
console.log('ArrowFunction arg a', a) | |
console.log('ArrowFunction arg a', b) | |
const lastArg = getLastArg(args) | |
console.log('ArrowFunction lastArg', lastArg) | |
} | |
var argToAppend = 'add-this-arg' | |
var newThis = { funky: 'hi' } | |
var extendedFunction = appendArguments(normalFunction, argToAppend, newThis) | |
extendedFunction(1, 2) | |
var extendedArrowFunction = appendArguments(arrowFunction, argToAppend) | |
extendedArrowFunction(3, 4) | |
/** | |
* Rebinding Arrow functions | |
*/ | |
function isArrowFunc(func){ | |
return typeof func === 'function' && func.toString().indexOf("=>") > -1 | |
} | |
// unsafe rebind arrow function | |
function arrowBind(context, fn) { | |
let arrowFn = fn; | |
(function() { | |
try { | |
arrowFn = eval(fn.toString()) | |
} catch (e) {} | |
}).call(context) | |
return arrowFn | |
} | |
var preBoundArrow = () => { | |
console.log(this) | |
} | |
preBoundArrow() | |
var newThisForArrow = { cool: 'hello'} | |
var reBound = arrowBind(newThisForArrow, preBoundArrow) | |
reBound() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment