Nodes suggestion for timed rolling average and desynchronised sum

Hi Colin,

your code is very useful. Thank you for this. Although it's working I get an error as follows:

Referring to the line below:

while (buffer[0] && buffer[0].timestamp < now - range)

it says:

The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.

How can I resolve this ?

Thank you...

Can you post the full code of the function you are using please?

Though probably you just need to change now to now.getTime()
The latest linter in node-red doesn't know about subtracting Date objects. The code will work as it is because the interpreter will call getTime() automatically.

I used your code from above (great btw) without any changes.

// determines the average of all payload values passed in 
// over the specified time range
const range = 20 * 60 * 1000;   // window time millisecs
let buffer = context.get('buffer') || [];
let total = context.get('total') || 0;   // the accumulated total so far

let now = new Date();
let value = Number(msg.payload);
// remove any samples that are too old
while (buffer[0] && buffer[0].timestamp < now - range) {
    // remove oldest sample from array and total
    node.warn(`removing oldest ${buffer[0].timestamp}`);
    total -= buffer[0].value;
    buffer.shift();
}
// add the new sample to the end
buffer.push({timestamp: now, value: value});
total += value;

context.set('buffer', buffer);
context.set('total', total);

msg.payload = total/buffer.length;
node.warn(`length: ${buffer.length}, total: ${total}, average: ${msg.payload}`);
return msg;

That was the solution!! Thank you so much!!

All the best....

One more short question do I have to adjust the declaration below also ? I.e. does 'let now...' should become 'let now.getTime()...' ?

Try it and see.