All files / math/internal snap-to-step.ts

100% Statements 13/13
100% Branches 2/2
100% Functions 2/2
100% Lines 13/13

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 20 21 22 23 24 25    9x 9x     27x 27x 27x 119x 119x   27x       27x 27x   27x 7x   27x    
import { roundToFractionDigits } from '../round-to-fraction-digits';
 
const TOLERANCE = 1e-9;
const DECIMAL_BASE = 10;
 
function countDecimals(step: number): number {
  let decimals = 0;
  let scaled = step;
  while (Math.abs(scaled - Math.round(scaled)) > TOLERANCE * scaled) {
    scaled *= DECIMAL_BASE;
    decimals += 1;
  }
  return decimals;
}
 
export function snapToStep(value: number, step: number, snap: (quotient: number) => number): number {
  let quotient = value / step;
  const nearest = Math.round(quotient);
  // 0.3 / 0.1 is 2.9999999999999996: snap it to 3 before flooring.
  if (Math.abs(quotient - nearest) <= TOLERANCE * Math.max(1, Math.abs(quotient))) {
    quotient = nearest;
  }
  return roundToFractionDigits(snap(quotient) * step, countDecimals(step));
}