From 6cfc67e728059cc36aa71d942f5966f4371125a3 Mon Sep 17 00:00:00 2001 From: Mikkel Laursen Date: Tue, 17 Nov 2020 18:33:03 -0700 Subject: [PATCH] fix(utils): updated nearest to support a custom range for sliders --- packages/form/src/slider/utils.ts | 2 +- packages/utils/src/__tests__/nearest.ts | 14 ++++++++++++++ packages/utils/src/nearest.ts | 5 +++-- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/packages/form/src/slider/utils.ts b/packages/form/src/slider/utils.ts index 768ef72dc0..460e03084c 100644 --- a/packages/form/src/slider/utils.ts +++ b/packages/form/src/slider/utils.ts @@ -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; diff --git a/packages/utils/src/__tests__/nearest.ts b/packages/utils/src/__tests__/nearest.ts index b5581a98cc..a63042fda3 100644 --- a/packages/utils/src/__tests__/nearest.ts +++ b/packages/utils/src/__tests__/nearest.ts @@ -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); + }); }); diff --git a/packages/utils/src/nearest.ts b/packages/utils/src/nearest.ts index 656ff17ed7..4119eda915 100644 --- a/packages/utils/src/nearest.ts +++ b/packages/utils/src/nearest.ts @@ -6,6 +6,7 @@ * @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 */ @@ -13,9 +14,9 @@ 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);