Sobes.tech
Junior — Senior

Creating a spy wrapper for any function

livecode

Task condition

Implement a function spy that takes another function and returns its wrapper, mimicking the behavior of the original. Besides executing, the wrapper should store information about each call: the number of calls in data.calls, an array of passed arguments in data.args, and the results obtained in data.results. Example usage:

 function _sum(a, b) {
    return a + b
}

function spy(f) {
    // YOUR CODE HERE
}

const sum = spy(_sum)

console.log(sum(2, 2)) // 4  
console.log(sum(21, 21)) // 42  
/* NUMBER OF CALLS TO THE _sum FUNCTION */  
console.log(sum.data.calls) // 2  
/* TIMES WHEN THE _sum FUNCTION WAS CALLED, IN ORDER */  
console.log(sum.data.args) // [(2, 2], [21, 21])  
/* RESULTS RETURNED BY THE _sum FUNCTION, IN ORDER */  
console.log(sum.data.results) // [4, 42]