Clamp a value and snap it to the nearest slider step
A range slider (a price filter, a volume knob, a thermostat) must turn whatever number the pointer or the keyboard produces into a value the slider can actually show: inside the range, and on one of its steps. Implement snapToRange(value, options), the normalization function behind such a slider.
snapToRange(value, { min, max, step? }) // => number
step: clamp value to [min, max], inclusive.step: the valid values are min, min + step, min + 2 * step, and so on, up to the largest one that is <= max. Steps start at min, not at 0. Return the valid value nearest to value.
value is exactly halfway between two valid values, pick the larger one.max itself may not be a valid value. For { min: 0, max: 100, step: 30 } the valid values are 0, 30, 60, 90, so anything large snaps to 90.NaN returns min. Infinity and -Infinity snap to the largest and smallest valid values.0.3, not 0.30000000000000004. The result is the valid value written with as many decimals as min, max, and step use (whichever uses the most).RangeError if min or max is not a finite number, if min > max, or if step is given and is not a finite number greater than 0.value is always a number. Option values use at most 10 decimals.snapToRange(140, { min: 0, max: 100 }); // => 100
snapToRange(-3, { min: 0, max: 100 }); // => 0
snapToRange(612, { min: 0, max: 1000, step: 25 }); // => 600
snapToRange(613, { min: 0, max: 1000, step: 25 }); // => 625
snapToRange(15, { min: 0, max: 100, step: 10 }); // => 20 (tie goes to the larger value)
snapToRange(12, { min: 5, max: 55, step: 10 }); // => 15 (steps are 5, 15, 25, ...)
snapToRange(98, { min: 0, max: 100, step: 30 }); // => 90 (100 is not on a step)
snapToRange(0.3, { min: 0, max: 1, step: 0.1 }); // => 0.3
snapToRange(1.1, { min: 0.25, max: 3, step: 0.5 }); // => 1.25
snapToRange(NaN, { min: 18, max: 30, step: 0.5 }); // => 18
snapToRange(1, { min: 10, max: 0 }); // throws RangeError