UNPKG

797 BJavaScriptView Raw
1export class VelocityTracker {
2 constructor() {
3 this.history = [];
4 this.lastPosition = undefined;
5 this.lastTimestamp = undefined;
6 }
7
8 add(position) {
9 const timestamp = new Date().valueOf();
10 if (this.lastPosition && timestamp > this.lastTimestamp) {
11 const diff = position - this.lastPosition;
12 if (diff > 0.001 || diff < -0.001) {
13 this.history.push(diff / (timestamp - this.lastTimestamp));
14 }
15 }
16 this.lastPosition = position;
17 this.lastTimestamp = timestamp;
18 }
19
20 estimateSpeed() {
21 const finalTrend = this.history.slice(-3);
22 const sum = finalTrend.reduce((r, v) => r + v, 0);
23 return sum / finalTrend.length;
24 }
25
26 reset() {
27 this.history = [];
28 this.lastPosition = undefined;
29 this.lastTimestamp = undefined;
30 }
31}