Created
November 17, 2017 19:50
-
-
Save t00n/57a4c351ec1beac9a42f9446513ed420 to your computer and use it in GitHub Desktop.
Modify JS function prototype to call functions with an object of arguments (similar to f(**dict) in Python)
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
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