データ列に対してmapすると移動平均が得られるフィルタ関数。chartjs が移動平均線の描画に対応してないっぽいが、これを噛ましてやれば自力で移動平均用のデータ列が作れる。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const movingAverageFilter = (ws=3) => { | |
if(!Number.isInteger(ws) || ws < 1) { | |
throw new Error(`Invalid window size. ws must be >=1. You entered: ws=${ws}.`) | |
} | |
let win = [] | |
let sum = 0 | |
let pos = 0 | |
let tail = 0 | |
return (head) => { | |
sum = sum + head - tail | |
win[pos] = head | |
pos = pos < ws - 1 ? pos + 1 : 0 | |
if(win.length < ws) { | |
return | |
} | |
tail = win[pos] | |
return sum/ws | |
} | |
} | |
// test | |
const data = [1,2,3,4,5,6,7,8,9,10]; | |
[1,2,3,5,10].forEach(ws => { | |
console.log(`ws=${ws}`, data.map(movingAverageFilter(ws))) | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment