Function count calls

后端 未结 5 1679
轻奢々
轻奢々 2021-01-12 22:24

I\'m a beginner with JavaScript so please be patient =)

I am trying to write a function that counts the number of times it is called. What I have so far is a functi

5条回答
  •  -上瘾入骨i
    2021-01-12 23:18

    Wrap a counter to any function:

    /**
     * Wrap a counter to a function
     * Count how many times a function is called
     * @param {Function} fn Function to count
     * @param {Number} count Counter, default to 1
     */
    function addCounterToFn(fn, count = 1) {
      return function () {
        fn.apply(null, arguments);
        return count++;
      }
    }
    

    See https://jsfiddle.net/n50eszwm/

提交回复
热议问题