JSFiddle - React, Tailwind, and code Playground

by Diana Lemen

JavaScript

class Accumulator {
	constructor(arr) {
		this.arr = arr;
    this.totalSum = 0;
	}
  
  async accumulate() {
  	this.totalSum = this.totalSum + 1;
  	const res = await this.arr.reduce(async (acc, el) => {
    	const val = await el;
      const acc2 = await acc;
    	return acc2 + val;
    }, Promise.resolve(0));
    
    return res;
  }
  
  total() {
  	return this.totalSum;
  }
  
  reset() {
  	this.totalSum = 0;
  }
}

const arr = [1,2,3,4,5,6,7,8,9,10].map(el => Promise.resolve(el));
const acc = new Accumulator(arr);
acc.accumulate();
acc.accumulate().then(res => console.log('test', res))
console.log(acc.total());
acc.accumulate().then(res => console.log('test', res))
console.log(acc.total());
acc.reset();
console.log(acc.total());
acc.accumulate().then(res => console.log('test', res))
console.log(acc.total());