Function count calls

后端 未结 5 1677
轻奢々
轻奢々 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条回答
  • 2021-01-12 22:58

    There are also the new Generator functions, which offer a simple way to write a counter:

    function* makeRangeIterator(start = 0, end = 100, step = 1) {
      let iterationCount = 0;
      for (let i = start; i < end; i += step) {
        iterationCount++;
        yield i;
      }
      return iterationCount;
    }
    
    const counter = makeRangeIterator();
    const nextVal = () => counter.next().value;
    
    console.log("nextVal: ", nextVal()); // 0
    console.log("nextVal: ", nextVal()); // 1
    console.log("nextVal: ", nextVal()); // 2
    console.log("nextVal: ", nextVal()); // 3
    
    0 讨论(0)
  • 2021-01-12 23:08

    A one liner option:

    const counter = ((count = 0) => () => count++)()
    

    Usage example:

    > counter()
    0
    > counter()
    1
    > counter()
    2
    > counter()
    3
    > counter()
    4
    > counter()
    5
    > counter()
    6
    
    0 讨论(0)
  • 2021-01-12 23:16
    var increment = function() {
        var i = 0;
        return function() { return i += 1; };
    };
    
    var ob = increment();
    
    0 讨论(0)
  • 2021-01-12 23:17
    ob = function f(){  
      ++f.i || (f.i=1);   // initialize or increment a counter in the function object
      return f.i; 
    }
    
    0 讨论(0)
  • 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/

    0 讨论(0)
提交回复
热议问题