Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Modify JS function prototype to call functions with an object of arguments (similar to f(**dict) in Python)
function function_params(func) {
if (typeof(func) == "function") {
let source_code = func.toString()
let regex_paren = new RegExp("\\((.*)\\)")
let args_str = regex_paren.exec(source_code)
return args_str[1].split(",").map((x) => x.trim())
}
}
Function.prototype.applyObj = function (obj) {
let func = this
let params = function_params(func)
return func.apply(null, params.map((x) => obj[x]))
}
// Testing
function f(a, b) {
console.log("f:", a, b)
}
const g = (a, b) => {
console.log("g:", a, b)
}
const h = function(a, b) {
console.log("h:", a, b)
}
// console.log(function_params(f))
// console.log(function_params(g))
// console.log(function_params(h))
console.log(f.applyObj({a: 5}))
console.log(g.applyObj({a: 5}))
console.log(h.applyObj({a: 5}))
console.log(f.applyObj({a: 5, b: 3}))
console.log(g.applyObj({a: 5, b: 3}))
console.log(h.applyObj({a: 5, b: 3}))
console.log(f.applyObj({a: 5, b: 3, c: 5}))
console.log(g.applyObj({a: 5, b: 3, c: 5}))
console.log(h.applyObj({a: 5, b: 3, c: 5}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.