| 6 | } |
| 7 | |
| 8 | function lttbIndicesForInterleavedXY(data: Float32Array, targetPoints: number): Int32Array { |
| 9 | const n = data.length >>> 1; // floor(length / 2) |
| 10 | const lastIndex = n - 1; |
| 11 | |
| 12 | if (targetPoints <= 0 || n === 0) return new Int32Array(0); |
| 13 | if (targetPoints === 1) return new Int32Array([0]); |
| 14 | if (targetPoints === 2) return n >= 2 ? new Int32Array([0, lastIndex]) : new Int32Array([0]); |
| 15 | if (n <= targetPoints) { |
| 16 | const indices = new Int32Array(n); |
| 17 | for (let i = 0; i < n; i++) indices[i] = i; |
| 18 | return indices; |
| 19 | } |
| 20 | |
| 21 | const indices = new Int32Array(targetPoints); |
| 22 | indices[0] = 0; |
| 23 | indices[targetPoints - 1] = lastIndex; |
| 24 | |
| 25 | const bucketSize = (n - 2) / (targetPoints - 2); |
| 26 | |
| 27 | let a = 0; |
| 28 | let out = 1; |
| 29 | |
| 30 | const lastX = data[lastIndex * 2 + 0]; |
| 31 | const lastY = data[lastIndex * 2 + 1]; |
| 32 | |
| 33 | for (let bucket = 0; bucket < targetPoints - 2; bucket++) { |
| 34 | // Current bucket: candidate points are [rangeStart, rangeEndExclusive) and never include lastIndex. |
| 35 | let rangeStart = Math.floor(bucketSize * bucket) + 1; |
| 36 | let rangeEndExclusive = Math.min(Math.floor(bucketSize * (bucket + 1)) + 1, lastIndex); |
| 37 | if (rangeStart >= rangeEndExclusive) { |
| 38 | // Defensive: ensure at least one candidate point. |
| 39 | rangeStart = Math.min(rangeStart, lastIndex - 1); |
| 40 | rangeEndExclusive = Math.min(rangeStart + 1, lastIndex); |
| 41 | } |
| 42 | |
| 43 | // Next bucket for average: [nextRangeStart, nextRangeEndExclusive) |
| 44 | const nextRangeStart = Math.floor(bucketSize * (bucket + 1)) + 1; |
| 45 | const nextRangeEndExclusive = Math.min(Math.floor(bucketSize * (bucket + 2)) + 1, lastIndex); |
| 46 | |
| 47 | // If there are no points in the next bucket, use the last point as the average. |
| 48 | let avgX = lastX; |
| 49 | let avgY = lastY; |
| 50 | if (nextRangeStart < nextRangeEndExclusive) { |
| 51 | let sumX = 0; |
| 52 | let sumY = 0; |
| 53 | let avgCount = 0; |
| 54 | for (let i = nextRangeStart; i < nextRangeEndExclusive; i++) { |
| 55 | sumX += data[i * 2 + 0]; |
| 56 | sumY += data[i * 2 + 1]; |
| 57 | avgCount++; |
| 58 | } |
| 59 | if (avgCount > 0) { |
| 60 | avgX = sumX / avgCount; |
| 61 | avgY = sumY / avgCount; |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | const ax = data[a * 2 + 0]; |