Woody P Lucas
Woody P Lucas

Reputation: 77

Having trouble using closures

I'm having trouble using closures to find the output average of every invocation.

If the argument is undefined set it to 0 only if the first invocation is undefined. If numbers are passed return the the average of the output.

function average() {
      let sum = 0;
      let count = 0;
      return function(num) {
        let increment = count++
        let avg;
        if(typeof num === "number" ) {
          sum += num;
          // avg = sum / increment
        } 
        return sum;
      }
    }
    
    // /*** Uncomment these to check your work! ***/
     const avgSoFar = average();
     console.log(avgSoFar()); // => should log 0
     console.log(avgSoFar(4)); // => should log 4
     console.log(avgSoFar(8)); // => should log 6
     console.log(avgSoFar()); // => should log 6
     console.log(avgSoFar(12)); // => should log 8
     console.log(avgSoFar()); // => should log 8

Upvotes: 2

Views: 48

Answers (1)

Unmitigated
Unmitigated

Reputation: 89214

You need to increment the count by one each time the function is called and divide the sum by the count to get the average.

function average() {
  let sum = 0;
  let count = 0;
  return function(num) {
    if(typeof num === "number" ) {
      sum += num;
      count++;
    } 
    return count != 0 ? sum / count: 0;
  }
}

// /*** Uncomment these to check your work! ***/
 const avgSoFar = average();
 console.log(avgSoFar()); // => should log 0
 console.log(avgSoFar(4)); // => should log 4
 console.log(avgSoFar(8)); // => should log 6
 console.log(avgSoFar()); // => should log 6
 console.log(avgSoFar(12)); // => should log 8
 console.log(avgSoFar()); // => should log 8

Upvotes: 2

Related Questions