There might be potential issues with daylight saving time due to the use of timestamps, which raises some doubts. Nonetheless, it seems to be functioning adequately. If certain sections of the code appear unconventional, it's likely because it was tailored to work efficiently with Solidity, lacking some of the more advanced features found in JavaScript.
The objective is to calculate the total volume over the last 7 days from a specific date:
class rollingWindow {
constructor() {
this.refTime = new Date("01/01/2023 00:00:00");
// bins - representing each day of the week (starting from Sunday)
this.distribution = {
0: { vol: 0, week: 0 },
1: { vol: 0, week: 0 },
2: { vol: 0, week: 0 },
3: { vol: 0, week: 0 },
4: { vol: 0, week: 0 },
5: { vol: 0, week: 0 },
6: { vol: 0, week: 0 }
};
}
}
rollingWindow.prototype.add = function (volume, datetime) {
let diff = (datetime.getTime() - this.refTime.getTime());
let bin = (diff / 1000/60/60/24) % 7;
bin = bin - (bin % 1); // flooring function
console.log("bin:" + bin); // represents the day of the week
const floorargm = diff / (7 * 24 * 60 * 60 * 1000)
let currentWeek = floorargm - (floorargm % 1)
console.log("Week:"+currentWeek);
if (this.distribution[bin].week < currentWeek) {
this.distribution[bin].vol = 0;
this.distribution[bin].week = currentWeek;
}
this.distribution[bin].vol += volume;
};
rollingWindow.prototype.get = function(datetime) {
let diff = (datetime.getTime() - this.refTime.getTime());
let bin = (diff / 1000/60/60/24) % 7;
bin = bin - (bin % 1); // flooring function
const floorargm = diff / (7 * 24 * 60 * 60 * 1000);
let currentWeek = floorargm - (floorargm % 1);
// summing up previous and current bins
let sum=0;
for (let i = bin; i >= 0; i--) {
if (this.distribution[i].week === currentWeek) {
sum+= this.distribution[i].vol;
}
if(i === 0) {
break;
}
}
// summing up subsequent bins
for (let i = bin + 1; i < 7;i++) {
if (this.distribution[i].week === currentWeek - 1) {
sum+= this.distribution[i].vol;
}
}
return sum;
}
let rolling = new rollingWindow()
rolling.add(1, new Date("01/01/2023 00:00:00"));
rolling.add(1, new Date("01/02/2023 00:00:00"));
rolling.add(1, new Date("01/02/2023 00:00:00"));
rolling.add(1, new Date("01/03/2023 00:00:00"));
rolling.add(1, new Date("01/04/2023 00:00:00"));
rolling.add(1, new Date("01/05/2023 00:00:00"));
rolling.add(1, new Date("01/06/2023 00:00:00"));
rolling.add(1, new Date("01/07/2023 00:00:00"));
rolling.add(1, new Date("01/08/2023 00:00:00"));
let sum = rolling.get(new Date("01/08/2023 00:00:00"));
console.log(sum);