All files / math smooth-towards.ts

100% Statements 3/3
100% Branches 2/2
100% Functions 1/1
100% Lines 3/3

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19                          13x 1x   12x    
/**
 * Moves a value towards a target with exponential smoothing, whatever the frame rate: about 63 % of the
 * distance is covered every `timeConstantMs`. Smooths a needle fed by noisy values.
 *
 * @param current - The displayed value.
 * @param target - The latest value.
 * @param deltaMs - The time elapsed since the previous call, in milliseconds.
 * @param timeConstantMs - The time constant, in milliseconds; `0` returns `target`.
 * @returns The new displayed value.
 * @example
 * needle = smoothTowards(needle, speed, deltaMs, 150);
 */
export function smoothTowards(current: number, target: number, deltaMs: number, timeConstantMs: number): number {
  if (timeConstantMs <= 0) {
    return target;
  }
  return target + (current - target) * Math.exp(-deltaMs / timeConstantMs);
}