Last active
May 2, 2022 13:47
-
-
Save nicanordlc/4ade8f2be5ade91e0393a56e6c116016 to your computer and use it in GitHub Desktop.
Util function to proxy a function arguments and do something with them (not harming the default function implementation)
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
/** | |
* hookInto | |
* | |
* This will hook into a function of an object so we can check the arguments | |
* used when it is called any time and do some calculations on those arguments. | |
* | |
* @param {object} targetObject Object where the function you want to target is | |
* @param {string} functionName The name of the function you want to target | |
* @param {function} handler The hook function that will handle the arguments | |
* @returns {undefined} | |
*/ | |
function hookInto(targetObject, functionName, handler = () = >{}) { | |
// save the original function | |
const backupFunction = targetObject[functionName] | |
// overwrite the original function and set the handler | |
targetObject[functionName] = function(...args) { | |
// handle the arguments with the custom handler | |
handler(...args) | |
// trigger the original function as normal | |
backupFunction.apply(targetObject, args) | |
} | |
} | |
// Example: | |
// hookInto(localStorage, 'setItem', (...args) => { console.log(args) }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment