Keep track of how many times a recursive function was called

后端 未结 9 1940
醉梦人生
醉梦人生 2021-02-02 05:03



        
9条回答
  •  深忆病人
    2021-02-02 05:46

    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);

提交回复
热议问题