Last active
May 27, 2024 22:33
-
-
Save SparK-Cruz/dc40179dd2132df2c9255983b15f552b to your computer and use it in GitHub Desktop.
This extension allows functions to be called via apply with an object as argument for simulating named parameter calls.
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
/** | |
* Usage: | |
* Similar to native "Function.prototype.apply" but supporting an object as second argument. | |
* | |
* Given the following function: | |
* ``` | |
* function myFunction(a, b = 2, c = 3, options = {complex: true}) { | |
* console.log(a, b, c, options); | |
* } | |
* ``` | |
* You can now do the following: | |
* ``` | |
* myFunction.apply(null, {b: 10, options: {complex: false}, a: "what?"}); | |
* ``` | |
* And have it output: `what? 10 3 { complex: false }` | |
* | |
* `((a, b, c) => { console.log(a, b, c); }).apply({}, {b: 10});` | |
* Outputs `undefined 10 undefined` | |
*/ | |
(() => { | |
const native = Function.prototype.apply; | |
Object.defineProperty(Function.prototype, "apply", { | |
enumerable: false, | |
configurable: false, | |
get() { | |
return function(thisObj, argsObj) { | |
if (Array.isArray(argsObj)) { | |
return native.call(this, thisObj, argsObj); | |
} | |
const match = this.toString().match(/^(?:function\s)?(?:\w[\w\d]*\s*)?\((.*)\)\s*(?:=>)?\s*{.*/); | |
let parameters = []; | |
if (match) { | |
parameters = match[1].replace(/=\s*[\{\(\[].*[\}\)\]]/, "").split(",").map(part => { | |
return part.split("=")[0].trim(); | |
}); | |
} | |
const args = parameters.map(param => { | |
return argsObj[param]; | |
}); | |
native.call(this, thisObj, args); | |
} | |
} | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment