Skip to content
Advertisement

How to Map/reduce a series of date bound values to a running total in JavaScript / RXJS?

I have an observable that emits measurement values with a date for a key. Something like:

JavaScript

I need a 7 days running total and average for temp and hum. If I would have a a value for each week, I could write:

JavaScript

However I need a running total where the values are accumulated like this:

JavaScript

How would I design a reducer for this? I’m open for alternative approaches

Advertisement

Answer

Something like this?

Here you do re-calculate the total each time. If there were more values or calculating the totals was computationally expensive, you could keep a stack of values and push/pop to subtract old values and push new ones. For a running total of 7, it’s faster to just recalculate with each emission.

I made the observable empty so that this toy example compiles. You’ll need to provide some data instead of an EMPTY stream.

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement