I'm learning decorators, and while I haven't been having good luck with tutorials, I tried to hack one myself and got this:
function sum(...args) { return [...args].reduce((sum,a)=> sum + a, 0) }
const decorate = (fn, callback) => (...args) => {
callback();
return fn(...args); // Return the result of the executed function
}
const running = () => console.log('Running')
const decoratedSum = decorate(sum, running)
console.log(decoratedSum(1,2,3)) // 'Running' // 6
I still had a tutorial post opened and instead of executing the function using f(arg) they use f.apply():
function sum(...args) { return [...args].reduce((sum,a)=> sum + a, 0) }
const wrap = (fn, callback) => function(){
callback();
return fn.apply(this, arguments);
}
const running = () => console.log('Running')
const wrappedSum = wrap(sum, running)
console.log(wrappedSum(1,2,3)) // 'Running' // 6
Is there a reason not to use decorate() over wrap()?
Also can someone please explain what's actually happening with fn.apply(this, arguements)?