UNPKG

mingo

Version:

MongoDB query language for in-memory objects

36 lines (35 loc) 1 kB
import { assert, isNumber } from "../../util"; import { $push } from "../accumulator/push"; import { withMemo } from "./_internal"; const $expMovingAvg = (_, collection, expr, options) => { const { input, N, alpha } = expr.inputExpr; assert( !(N && alpha), `You must specify either N or alpha. You cannot specify both.` ); return withMemo( collection, expr, () => { const weight = N != void 0 ? 2 / (N + 1) : alpha; const values = $push(collection, input, options); for (let i = 0; i < values.length; i++) { if (i === 0) { if (!isNumber(values[i])) values[i] = null; continue; } if (!isNumber(values[i])) { values[i] = values[i - 1]; continue; } if (!isNumber(values[i - 1])) continue; values[i] = values[i] * weight + values[i - 1] * (1 - weight); } return values; }, (series) => series[expr.documentNumber - 1] ); }; export { $expMovingAvg };