Skip to content

Commit

Permalink
fix(utils): updated nearest to support a custom range for sliders
Browse files Browse the repository at this point in the history
  • Loading branch information
mlaursen committed Dec 15, 2020
1 parent c4ee05b commit 6cfc67e
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 3 deletions.
2 changes: 1 addition & 1 deletion packages/form/src/slider/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ export const getDragValue = ({
const range = max - min;
const steps = getSteps(min, max, step);
const value = percentageDragged * range + min;
const rounded = nearest(value, minValue, maxValue, steps);
const rounded = nearest(value, minValue, maxValue, steps, range);

if (!vertical && isRtl) {
return steps - rounded;
Expand Down
14 changes: 14 additions & 0 deletions packages/utils/src/__tests__/nearest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,18 @@ describe("nearest", () => {
expect(nearest(0.28, 0, 1, 4)).toBe(0.25);
expect(nearest(0.33, 0, 1, 4)).toBe(0.25);
});

it("should allow for a custom range to be used with range sliders", () => {
// to explain this a bit better, need to make sure that the slider thumbs
// are always in order of `min -> max` so the min and max values change
// depending on which thumb is being dragged:
// - thumb1 -> min === min, max === thumb2Value
// - thumb2 -> min === thumb1Value, max === max

expect(nearest(44.3, 40, 100, 100, 100)).toBe(44);
expect(nearest(50, 20, 50, 50, 50)).toBe(50);
expect(nearest(22.3, 20, 50, 50, 50)).toBe(22);
expect(nearest(12.3, 20, 50, 50, 50)).toBe(20);
expect(nearest(0, 30, 50, 100, 100)).toBe(30);
});
});
5 changes: 3 additions & 2 deletions packages/utils/src/nearest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,17 @@
* @param min The min value allowed
* @param max The max value allowed
* @param steps The number of steps in the min/max range
* @param range The range allowed for the value that defaults to `max - min`
* @return the value rounded to the nearest step in the min/max range
* @since 2.5.0 - Added the `range` param
*/
export function nearest(
value: number,
min: number,
max: number,
steps: number
steps: number,
range = max - min
): number {
const range = max - min;
const rounded = Math.round(((value - min) * steps) / range) / steps;
const zeroToOne = Math.min(Math.max(rounded, 0), 1);

Expand Down

0 comments on commit 6cfc67e

Please sign in to comment.