如何在 JavaScript / RXJS 中 Map/reduce 一系列日期绑定值到 运行 总数?
How to Map/reduce a series of date bound values to a running total in JavaScript / RXJS?
我有一个 observable 可以发出带有日期的测量值作为键。类似于:
{ "date" : "2021-11-01",
"temp" : 23.4,
"hum" : 74.5
}
我需要 7 天 运行 的总计和 temp
和 hum
的平均值。如果我每周都有一个值,我可以写:
const weeklyReducer = (accumulator, currentValue, index) => {
const key = Math.floor((index-1)/7);
const workValue = accumulator[key] || {key, temp: 0, hum:0};
workValue.temp = workValue.temp + currentValue.temp;
workValue.hum = workValue.hum + currentValue.hum;
accumulator[key] = workValue;
return accumulator;
}
但是我需要一个 运行 总数,其中的值是这样累积的:
Running total 1: 1
Running total 2: 1,2
...
Running total 7: 1,2,3,4,5,6,7
Running total 8: 2,3,4,5,6,7,8
Running total 9: 3,4,5,6,7,8,9
Running total 10: 4,5,6,7,8,9,10
我将如何为此设计减速器?
我愿意接受其他方法
是这样的吗?
这里每次都重新计算总数。如果有更多的值或计算总计的计算量很大,您可以保留一堆值和 push/pop 来减去旧值并压入新值。对于 运行 总共 7 个,每次发射重新计算会更快。
我将 observable 设为空,以便编译这个玩具示例。您需要提供一些数据而不是 EMPTY
流。
interface measurement {
date : string,
temp : number,
hum : number
}
let measurements$: Observable<measurement> = EMPTY;
measurements$.pipe(
scan((acc, curr) => [...acc.slice(-6), curr], [] as measurement[]),
map(measurements => ({
runningDates: measurements.map(({date}) => date),
totalTemp: measurements.reduce((acc,{temp}) => acc + temp, 0),
totalHum: measurements.reduce((acc,{hum}) => acc + hum, 0),
}))
).subscribe(console.log);
我有一个 observable 可以发出带有日期的测量值作为键。类似于:
{ "date" : "2021-11-01",
"temp" : 23.4,
"hum" : 74.5
}
我需要 7 天 运行 的总计和 temp
和 hum
的平均值。如果我每周都有一个值,我可以写:
const weeklyReducer = (accumulator, currentValue, index) => {
const key = Math.floor((index-1)/7);
const workValue = accumulator[key] || {key, temp: 0, hum:0};
workValue.temp = workValue.temp + currentValue.temp;
workValue.hum = workValue.hum + currentValue.hum;
accumulator[key] = workValue;
return accumulator;
}
但是我需要一个 运行 总数,其中的值是这样累积的:
Running total 1: 1
Running total 2: 1,2
...
Running total 7: 1,2,3,4,5,6,7
Running total 8: 2,3,4,5,6,7,8
Running total 9: 3,4,5,6,7,8,9
Running total 10: 4,5,6,7,8,9,10
我将如何为此设计减速器? 我愿意接受其他方法
是这样的吗?
这里每次都重新计算总数。如果有更多的值或计算总计的计算量很大,您可以保留一堆值和 push/pop 来减去旧值并压入新值。对于 运行 总共 7 个,每次发射重新计算会更快。
我将 observable 设为空,以便编译这个玩具示例。您需要提供一些数据而不是 EMPTY
流。
interface measurement {
date : string,
temp : number,
hum : number
}
let measurements$: Observable<measurement> = EMPTY;
measurements$.pipe(
scan((acc, curr) => [...acc.slice(-6), curr], [] as measurement[]),
map(measurements => ({
runningDates: measurements.map(({date}) => date),
totalTemp: measurements.reduce((acc,{temp}) => acc + temp, 0),
totalHum: measurements.reduce((acc,{hum}) => acc + hum, 0),
}))
).subscribe(console.log);