seasonalityIndex = (data, valueKey, dateKey, seasonalityDateFormat) => {
const distinctUnits = Array.from(new Set(data.map(d => d[dateKey]).map(d => seasonalityDateFormat(d))));
const unitMeans = d3.rollup(data, v => d3.mean(v, d => d[valueKey]), d => seasonalityDateFormat(d[dateKey]));
const overallAverage = d3.mean(Array.from(unitMeans), d => d[1]);
const unitSeasonalityIndex = d3.rollup(unitMeans, v => v[0][1] / overallAverage, d => d[0]);
return data.map(d => {
const unit = seasonalityDateFormat(d[dateKey])
const index = unitSeasonalityIndex.get(unit)
return {
...d,
seasonality: d[valueKey] / index
}
});
}