All files / utils snap.ts

100% Statements 18/18
100% Branches 8/8
100% Functions 3/3
100% Lines 14/14

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 262x 2x 6x   1x 1x   1x 9x   9x 19x 19x   19x   18x   12x   10x          
export const snap = (points: number | number[]) => {
  if (typeof points === 'number') {
    return (v: number) => Math.round(v / points) * points;
  } else {
    let i = 0;
    const numPoints = points.length;
 
    return (v: number) => {
      let lastDistance = Math.abs(points[0] - v);
 
      for (i = 1; i < numPoints; i++) {
        const point = points[i];
        const distance = Math.abs(point - v);
 
        if (distance === 0) return point;
 
        if (distance > lastDistance) return points[i - 1];
 
        if (i === numPoints - 1) return point;
 
        lastDistance = distance;
      }
    };
  }
};