JSFiddle - React, Tailwind, and code Playground
JavaScript
function inject(before, fn) {
return function(){
before.apply(this, arguments);
fn.apply (this, arguments);
}
}
function add(a, b) {
return a+ b;
}
function concat(a, b) {
return a + b;
}
/**
* You can repeat index and type to check multiple arguments
*/
function createArgumentChecker(index, type) {
var originalArgs = arguments;
return function() {
for (var i=0; i < originalArgs.length; i+=2) {
if (typeof arguments[ originalArgs[i] ] != originalArgs[i+1]) {
console.log("Invalid argument passed at index " + i +
". Expected type " + originalArgs[i+1] + "but it's " + typeof arguments[ originalArgs[i] ] );
}
}
}
}
function logArguments() {
console.log(this, arguments);
}
// Inject an argument checker
add = inject(add, createArgumentChecker(0,"number", 1, "number"));
concat = inject (concat, createArgumentChecker(0, "string", 1, "string"));
// You can even do it multiple times, inject an argument logger;
add = inject(add, logArguments);
concat = inject(concat, logArguments);
add(2,3);
add("2","3");
concat(2,3);
concat("2", "3");