You can use closure for this.
Just simply store counter
into the closure of function.
Here is example:
function singleDigitDecorator() {
let counter = 0;
return function singleDigitWork(num, isCalledRecursively) {
// Reset if called with new params
if (!isCalledRecursively) {
counter = 0;
}
counter++; // *
console.log(`called ${counter} times`);
let number = [...(num + "")].map(Number).reduce((x, y) => {
return x * y;
});
if (number <= 9) {
console.log(number);
} else {
console.log(number);
return singleDigitWork(number, true);
}
};
}
const singleDigit = singleDigitDecorator();
singleDigit(39);
console.log('`===========`');
singleDigit(44);