-
Notifications
You must be signed in to change notification settings - Fork 2
/
extrapolator.js
32 lines (26 loc) · 948 Bytes
/
extrapolator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
let gasPriceHistory = []
const extrapolate = (details, currentGasPrice) => {
gasPriceHistory.push(currentGasPrice)
gasPriceHistory = gasPriceHistory.slice(
Math.max(gasPriceHistory.length - details.extrapolationHistory, 0)
)
return calculate(gasPriceHistory)
}
const calculate = (ys) => {
if (ys.length === 0) {
throw new Error('Attempted to extrapolate with no data points')
} else if (ys.length === 1) {
return ys[0]
}
const n = ys.length
const xs = Array.from(Array(n).keys())
// Calculate the slope with least squares
// https://en.wikipedia.org/wiki/Simple_linear_regression#Numerical_example
const Sx = xs.reduce((a, b) => a + b, 0)
const Sy = ys.reduce((a, b) => a + b, 0)
const Sxx = xs.reduce((a, b) => a + b * b, 0)
const Sxy = ys.reduce((a, b, i) => a + b * xs[i], 0)
const slope = (n * Sxy - Sx * Sy) / (n * Sxx - Sx * Sx)
return ys[n - 1] + slope
}
exports.extrapolate = extrapolate