6 hour Stats projection

Hello,

Can anyone help me with the projection to emit a new event every 6 hour.
CampaignReportCreatedEvent occurs every hour. so i want to continue state.clicks += 1 until 6 hour reaches and then emit the total count to new event stream.

I am having hard time figuring this one out.

fromStream('report_campaign-1')
  // fromCategory('report_campaign')
  //   .foreachStream()
  //  .partitionBy(function(ev) {
  //       return ev.body.reportCampaign.campaignId
  //   })
  .when({
    $init: function(state, ev) {
      return {
        count: 0,
        countEmit: 0,
        emit: [],
        metrics: { cost: 0, clicks: 0, createdAt: null },
      };
    },
    $any: function(state, ev) {

      state.count += 1;

      if (state.lastPush) {
        const newDate = new Date(ev.body.reportCampaign.reportDate)
          , lastDate = new Date(state.lastPush)
          , difference = (newDate.getTime() - lastDate.getTime()) / (1000 * 60 * 60);


        if (difference <= 6) {
          state.countEmit += 1;
          state.emit.push({difference: difference, newDate: newDate, lastDate: lastDate});
          state.metrics.cost += ev.body.reportCampaign.cost;
          state.metrics.clicks += ev.body.reportCampaign.clicks;
          
          // set last push
          state.lastPush = new Date();

          // emit new stream
        }
        
      } else {
          state.metrics.cost += ev.body.reportCampaign.cost;
          state.metrics.clicks += ev.body.reportCampaign.clicks;
        //   state.metrics.createdAt = new Date();
          state.lastPush = ev.body.reportCampaign.reportDate;
      }

      return state;

    },
  });

Thank you in advance!

oblutu,

Just had a quick scan over this.
See the code:

state.lastPush = new Date();

Would you really want to do that after every event that arrives under 6 hours?
You would need to keep the initial datetime to remeber when the 6 hours had expired?