| 1 | import {_limitValue, _lookupByKey, isNullOrUndef, resolve} from '../helpers/index.js'; |
| 2 | |
| 3 | function lttbDecimation(data, start, count, availableWidth, options) { |
| 4 | /** |
| 5 | * Implementation of the Largest Triangle Three Buckets algorithm. |
| 6 | * |
| 7 | * This implementation is based on the original implementation by Sveinn Steinarsson |
| 8 | * in https://github.com/sveinn-steinarsson/flot-downsample/blob/master/jquery.flot.downsample.js |
| 9 | * |
| 10 | * The original implementation is MIT licensed. |
| 11 | */ |
| 12 | const samples = options.samples || availableWidth; |
| 13 | // There are less points than the threshold, returning the whole array |
| 14 | if (samples >= count) { |
| 15 | return data.slice(start, start + count); |
| 16 | } |
| 17 | |
| 18 | const decimated = []; |
| 19 | |
| 20 | const bucketWidth = (count - 2) / (samples - 2); |
| 21 | let sampledIndex = 0; |
| 22 | const endIndex = start + count - 1; |
| 23 | // Starting from offset |
| 24 | let a = start; |
| 25 | let i, maxAreaPoint, maxArea, area, nextA; |
| 26 | |
| 27 | decimated[sampledIndex++] = data[a]; |
| 28 | |
| 29 | for (i = 0; i < samples - 2; i++) { |
| 30 | let avgX = 0; |
| 31 | let avgY = 0; |
| 32 | let j; |
| 33 | |
| 34 | // Adding offset |
| 35 | const avgRangeStart = Math.floor((i + 1) * bucketWidth) + 1 + start; |
| 36 | const avgRangeEnd = Math.min(Math.floor((i + 2) * bucketWidth) + 1, count) + start; |
| 37 | const avgRangeLength = avgRangeEnd - avgRangeStart; |
| 38 | |
| 39 | for (j = avgRangeStart; j < avgRangeEnd; j++) { |
| 40 | avgX += data[j].x; |
| 41 | avgY += data[j].y; |
| 42 | } |
| 43 | |
| 44 | avgX /= avgRangeLength; |
| 45 | avgY /= avgRangeLength; |
| 46 | |
| 47 | // Adding offset |
| 48 | const rangeOffs = Math.floor(i * bucketWidth) + 1 + start; |
| 49 | const rangeTo = Math.min(Math.floor((i + 1) * bucketWidth) + 1, count) + start; |
| 50 | const {x: pointAx, y: pointAy} = data[a]; |
| 51 | |
| 52 | // Note that this is changed from the original algorithm which initializes these |
| 53 | // values to 1. The reason for this change is that if the area is small, nextA |
| 54 | // would never be set and thus a crash would occur in the next loop as `a` would become |
| 55 | // `undefined`. Since the area is always positive, but could be 0 in the case of a flat trace, |
| 56 | // initializing with a negative number is the correct solution. |
| 57 | maxArea = area = -1; |
| 58 | |
| 59 | for (j = rangeOffs; j < rangeTo; j++) { |
| 60 | area = 0.5 * Math.abs( |