Skip to content

A full-featured download manager.

3.6 KB
Raw Blame
import type { SpeedPoint } from '@shared/types/stats'

export { formatSpeed } from '@shared/utils/format-bytes'

export const SPEED_CHART_MIN_POINTS = 24
const DEFAULT_STEP_MS = 1_000

export function normalizeSpeedHistory(
  history: readonly SpeedPoint[],
  minPoints = SPEED_CHART_MIN_POINTS
): readonly SpeedPoint[] {
  if (history.length >= minPoints) return history

  const firstPoint = history[0]
  const secondPoint = history[1]
  const step =
    firstPoint && secondPoint
      ? Math.max(1, secondPoint.t - firstPoint.t)
      : DEFAULT_STEP_MS
  const paddingCount = minPoints - history.length
  const firstTimestamp = firstPoint?.t ?? Date.now()
  const padding = Array.from({ length: paddingCount }, (_, index) => ({
    t: firstTimestamp - (paddingCount - index) * step,
    down: 0,
    up: 0,
  }))

  return [...padding, ...history]
}

/** Select observed points by triangle area, retaining endpoints and the peak. */
export function sampleSpeedHistory(
  history: readonly SpeedPoint[],
  maxPoints: number,
  direction: 'up' | 'down'
): readonly SpeedPoint[] {
  const limit = Math.max(3, Math.floor(maxPoints))
  if (history.length <= limit) return history

  const peakIndex = history.reduce(
    (peak, point, index) =>
      point[direction] > history[peak][direction] ? index : peak,
    0
  )
  const bucketSize = (history.length - 2) / (limit - 2)
  const sampled = [history[0]]
  let previous = history[0]

  for (let bucket = 0; bucket < limit - 2; bucket++) {
    const start = Math.floor(bucket * bucketSize) + 1
    const end = Math.floor((bucket + 1) * bucketSize) + 1
    const nextEnd = Math.min(
      Math.floor((bucket + 2) * bucketSize) + 1,
      history.length
    )
    let averageTime = 0
    let averageSpeed = 0
    for (let index = end; index < nextEnd; index++) {
      averageTime += history[index].t
      averageSpeed += history[index][direction]
    }
    averageTime /= nextEnd - end
    averageSpeed /= nextEnd - end

    let selected = start
    let largestArea = -1
    for (let index = start; index < end; index++) {
      const point = history[index]
      const area = Math.abs(
        (previous.t - averageTime) * (point[direction] - previous[direction]) -
          (previous.t - point.t) * (averageSpeed - previous[direction])
      )
      if (area > largestArea) {
        largestArea = area
        selected = index
      }
    }
    if (peakIndex >= start && peakIndex < end) selected = peakIndex
    previous = history[selected]
    sampled.push(previous)
  }

  sampled.push(history[history.length - 1])
  return sampled
}

export function normalizeObservedSpeedHistory<T extends SpeedPoint>(
  history: readonly T[],
  maxPoints: number
): readonly T[] {
  const ordered = [...history].sort((left, right) => left.t - right.t)
  const cap = Math.max(0, Math.floor(maxPoints))
  if (cap === 0) return []
  return ordered.length > cap ? ordered.slice(-cap) : ordered
}

export function activityTimeDomain(
  history: readonly SpeedPoint[]
): readonly [number, number] | null {
  if (history.length === 0) return null
  const timestamps = history
    .map((point) => point.t)
    .filter(Number.isFinite)
    .sort((left, right) => left - right)
  const first = timestamps[0]
  const last = timestamps.at(-1)
  if (first === undefined || last === undefined) return null
  if (first === last) return [first - 500, first + 500]
  return [first, last]
}

export function chartCeiling(value: number): number {
  if (!Number.isFinite(value) || value <= 0) return 1
  const power = 10 ** Math.floor(Math.log10(value))
  const normalized = value / power
  const step = normalized <= 2 ? 2 : normalized <= 5 ? 5 : 10
  return step * power
}