// ๐ saveCallHistory.js
const {log} = console;
// throttle decorator
function saveCallHistory(f){
// โญ๏ธ save call history (arguments) here
let history = [];
// ๐ธ wrapper.history (getter)
Object.defineProperty(wrapper, 'history', {
get() { return history }
})
return wrapper;
// โญ๏ธ decorated function
function wrapper(...args){
history.push(args); // save arguments first
return f.apply(this, args);
}
}
// export
module.exports = { saveCallHistory }
// ๐ index.js
const { saveCallHistory } = require('./saveCallHistory.js');
// function
function f(...args) {
return args.join();
}
// object
let user = {
// method
say(...args) { return args.join() }
};
// โญ๏ธ decorator: "saveCallHistory"
// โญ๏ธ make function/method save call history
f = saveCallHistory(f);
user.say = saveCallHistory(user.say);
// log
[
f(1),
f(1,2),
f.history, // [ [ 1 ], [ 1, 2 ] ]
user.say(0),
user.say(2, 3),
user.say(4, 5, 6),
user.say.history, // [ [ 0 ], [ 2, 3 ], [ 4, 5, 6 ] ]
].forEach(x => console.log(x));