rolling window volume distribution

My goal is to track volume distribution on a daily basis within a 7-day window.

For instance, during the first week:

  • On Monday, I receive 4 items at various times,
  • followed by 3 items on Tuesday, and so on

which also involves state changes accordingly.

Mon Tue Wed Thu Fri Sat Sun
4 3 5 0 4 3 1

The challenge arises when the second week begins, where I want Monday's count to reset to 0 while preserving the counts of other days. The same pattern repeats for each new day in the week. Is there an efficient way to accomplish this?

I can easily determine the "bin" for item placement using the modulo operator, but I'm struggling with tracking the start of each day from 0 when a "new Monday" arrives (and continuing the count from there).

Answer №1

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);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to dynamically validate the fields and generate an array?

Currently in my Angular application, I've successfully implemented a pivot table using pivot.js. Now, I am faced with the task of loading all the indexes from elastic search whenever the user switches the index. Once the index is changed, the corresp ...

What is the best way to utilize mapping and filtering distinct values in an array using TypeScript?

What is the best way to filter and map distinct elements from an array into another array? I've experimented with various methods but keep encountering a syntax error stating "Illegal return statement". My objective is to display only unique items f ...

Exploring Angular 2 with ng-bootstrap Library

As I delve into learning Angular2, my goal is to incorporate ng-bootstrap into my project. However, I have encountered issues when trying to import ng-bootstrap and create a functional project. Being a novice in this field, I am unsure if the problem lies ...

What could be preventing the fill color of my SVG from changing when I hover over it?

I am currently utilizing VueJS to design an interactive map showcasing Japan. The SVG I am using is sourced from Wikipedia. My template structure is illustrated below (The crucial classes here are the prefecture and region classes): <div> <svg ...

JavaScript time zone error specific to Internet Explorer

In my code, I am attempting to retrieve the timezone name or ID based on the client's local time. When testing with clients from the United States, I correctly receive EDT. However, when trying the same code with clients in the Indian timezone, it ret ...

What is the best way to ensure that my program runs nonstop?

Is there a way to have my program continuously run? I want it to start over again after completing a process with a 2-second delay. Check out my code snippet below: $(document).ready(function () { var colorBlocks = [ 'skip', 'yell ...

Uncovered event listener in Angular tests

Imagine having a custom directive: angular.module('foo').directive('myDir', function () { return { restrict: 'E', link: function (scope) { var watcher = scope.$watch('foo, function () {}); scope.$on ...

Try utilizing the QUERY function in conjunction with PIVOT to ensure that the total sum of the empty fields

https://i.sstatic.net/WMxSs.png https://i.sstatic.net/ffKEh.png I discovered that inputting zeros into the shared sheet greatly improves the appearance of the Radar chart. https://docs.google.com/spreadsheets/d/19rP-xmEsL11SyQg-2f8VGlyyZ33KbnWJogdqs_Di1N ...

What sets apart the comparison `$a = (true === !!array_intersect(['1'],[3,2,1]));` from using the `in_array` function?

Situations for Utilization:- $a = (true === !!array_intersect(['1'], [3, 2, 1])); Indications for Usage $b = in_array('1', [3,2,1]); Both functions provide identical results. ...

Arranging elements in ascending order in Java

I've been attempting to arrange an array in ascending order, following the instructions in example 104.5. Despite carefully reviewing my code multiple times, I'm unable to identify the mistake. Below is the code snippet from my sorting class: imp ...

Unlocking the Chrome performance tool summary using SeleniumDiscovering the Chrome performance tool

I'm looking to utilize the Chrome performance tool for analyzing my website and then extract a summary of the results using Selenium WebDriver in Java. Despite extensive searching, I haven't been able to find a suitable solution yet. To give you ...

Automatically reload main page in Javascript upon closing child window (popup)

I am working with 3 php files: view.php, edit.php, and edit2.php. In view.php, I display the content of my database tables. edit.php is used to edit a specific row using textboxes, while edit2.php is responsible for updating changes in the database. Once ...

What is a way to retain the value of a variable after a request, while starting off with a different value on the initial load?

In my Flask application, users have the option to choose a specific time period with a start date and an end date. When the page initially loads, I want the start date to default to the first day of the current month and the end date to be the current day. ...

Is there a way to use Javascript to detect if the value of a control on an ASP.Net page has been modified?

Within my web page, I have integrated a FormView that transitions to Edit mode when the user clicks the edit button. To enhance user experience, I have implemented a JavaScript onbeforeunload function that triggers a confirmation dialog if the user tries t ...

Troubleshooting: Why is my AngularJS Controller not functioning properly

I attempted to run a basic Angular example utilizing a controller, but it does not appear to be functioning correctly. Below is the HTML code: <!DOCTYPE html> <html ng-app = "app"> <head> <title></title> ...

The JQuery(document).ready function does not seem to be executing on the webpage, but it works as expected when placed in a

I have encountered a peculiar problem. It's strange to me because I can't figure out the root cause of it, despite trying everything in the Chrome Developer Tools debugger. Here is a snippet of code that works when I run it from a file on my desk ...

Chrome renders the javascript source file in a jumbled and unreadable format

I'm new to a project and I've noticed that the javascript files I edit in my IDE appear differently in Chrome. For instance, here is a code snippet from Intellij: https://i.sstatic.net/1ygfg.png Even though this code is in a file named MNV.js, ...

Creating a List with Sublists that are displayed when hovering over the parent List is a key element of effective design

Hovering over 'View Rows' should open up both New Records and Old Records <div> <li>Add Rows</li> <li>DeleteRows</li> <li>View Rows <ul> <li>View New Records</li ...

Google Maps is experiencing difficulties maintaining its longitude and latitude coordinates within the Bootstrap tabbed user interface

I implemented ACF's Google Map to display a map on my webpage. I followed the instructions closely and made some minor modifications to the map js for styling purposes. One key change I had to make was in this section to ensure the map loads correctly ...

What is the process for searching a sentence and making replacements under certain conditions?

When it comes to the address: _# _, and for the specified phrase: _# some specific words _. I am looking to identify a phrase. if (phrase includes address) then delete the address. const stringVal = "being _#kind_, I am a _#kind_ _#man_, I love _#kind ...