parseStateData = key => {
const state = presidentByState.get(key);
const margins = state.timeseries
.filter(({ votes }) => votes)
.map(({ votes, vote_shares, timestamp }) => ({
a: Math.round(vote_shares[a.candidate_key] * votes),
b: Math.round(vote_shares[b.candidate_key] * votes),
timestamp: new Date(timestamp)
}))
.map(({ a, b, timestamp }, i, arr) =>
!i
? { da: a, db: b, timestamp }
: { da: a - arr[i - 1].a, db: b - arr[i - 1].b, timestamp }
)
.map(({ da, db, timestamp }) => ({ margin: da - db, timestamp, key }))
.filter(
({ timestamp }) =>
xUpperBoundOption === "mostRecent" ||
(timestamp >= electionNight[0] && timestamp <= electionNight[1])
);
const marginsArrays = margins.map(({ margin, timestamp }) => [
+timestamp,
margin
]);
const corr =
marginsArrays.length > 2
? stats.sampleCorrelation(...d3.transpose(marginsArrays))
: 0;
const regressionFn = stats.linearRegressionLine(
stats.linearRegression(marginsArrays)
);
const regressionLine = d3
.extent(margins, d => d.timestamp)
.map(d => ({ timestamp: d, margin: regressionFn(+d) }));
return [key, { margins, marginsArrays, corr, regressionLine }];
}