forked from ratik/wt-curvepoint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
66 lines (62 loc) · 1.95 KB
/
index.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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
var TRAFFIC_CURVE = '\
M0,190 C25,190 19,20 27,20 C35,20 31,109 36,109 C41,109 39,40 44,40\
C49,40 51,89 56,89 C61,89 59,24 65,24 C71,24 81,148 85,148\
C89,148 87,111 90,111 C93,111 94,190 100,190';
var parseCurve = (function(curve) {
function cubicBizier(t, dots) {
return Math.pow(1 - t, 3) * dots[0] +
3 * t * Math.pow(1 - t, 2) * dots[1] +
3 * Math.pow(t, 2) * (1 - t) * dots[2] +
Math.pow(t, 3) * dots[3];
}
var dailyCurveData = (function(curve) {
return curve.trim().split(' C').map(function(group) {
return group.trim().split(' ').map(function(coords) {
return coords.trim().split(',').map(function(value) {
return parseFloat(value.replace(/[^0-9.]/, '')) / 100;
});
});
}).reduce(function(acc, cur, index, array) {
return index > 0
? [].concat(acc, [[].concat(array[index - 1].slice(-1), cur)])
: acc;
}, []);
})(curve);
var cache = [];
return function(x) {
if (cache[x]) return cache[x];
if (x < 0 || x > 1 ) throw 'x should be [0,1]';
var tolerance = 1 / 1000;
var part = dailyCurveData.reduce(function(acc, cur) {
return x >= cur[0][0] && x <= cur[3][0] ? cur : acc;
}, 0);
function calcCoords(t) {
return {
x: cubicBizier(t, [ part[0][0], part[1][0], part[2][0], part[3][0] ]),
y: cubicBizier(t, [ part[0][1], part[1][1], part[2][1], part[3][1] ]),
};
}
var lower = 0;
var upper = 1;
var t = null;
var dot = null;
do {
t = (upper + lower) / 2;
dot = calcCoords(t);
if (x > dot.x) {
lower = t;
} else {
upper = t;
}
} while (Math.abs(x - dot.x) > tolerance);
cache[x] = parseFloat(dot.y.toFixed(2));
return cache[x];
}
});
module.exports = {
parseCurve: parseCurve,
calcTraffRatio: function(time) {
// time ∈ [0,1] = day traffic factor
return 2 - parseCurve(TRAFFIC_CURVE)(time);
}
}