diff --git a/lib/numeric-slider.tsx b/lib/numeric-slider.tsx index 68c2e1c..98f8e89 100644 --- a/lib/numeric-slider.tsx +++ b/lib/numeric-slider.tsx @@ -1,14 +1,11 @@ import React from "react"; -import { float, slugify } from "./util"; +import { float, NumericRange, slugify } from "./util"; -export type NumericSliderProps = { +export type NumericSliderProps = NumericRange & { id?: string; label: string; onChange: (value: number) => void; value: number; - min: number; - max: number; - step: number; valueSuffix?: string; }; diff --git a/lib/util.test.tsx b/lib/util.test.tsx index 0c912cd..9974953 100644 --- a/lib/util.test.tsx +++ b/lib/util.test.tsx @@ -1,4 +1,4 @@ -import { flatten, float, rad2deg, range } from "./util"; +import { flatten, float, inclusiveRange, rad2deg, range } from "./util"; describe("float", () => { it("converts strings", () => { @@ -31,3 +31,7 @@ test("range() works", () => { expect(range(1)).toEqual([0]); expect(range(5)).toEqual([0, 1, 2, 3, 4]); }); + +test("inclusiveRange() works", () => { + expect(inclusiveRange({ min: 0, max: 1, step: 0.5 })).toEqual([0, 0.5, 1]); +}); diff --git a/lib/util.ts b/lib/util.ts index 7603586..9eb187b 100644 --- a/lib/util.ts +++ b/lib/util.ts @@ -28,17 +28,31 @@ export function rad2deg(radians: number): number { return (radians * 180) / Math.PI; } +export type NumericRange = { + min: number; + max: number; + step: number; +}; + +/** + * Return numbers within the given range, inclusive. + */ +export function inclusiveRange({ min, max, step }: NumericRange): number[] { + const result: number[] = []; + + for (let i = min; i <= max; i += step) { + result.push(i); + } + + return result; +} + /** * Return an array containing the numbers from 0 to one * less than the given value, increasing. */ export function range(count: number): number[] { - const result: number[] = []; - for (let i = 0; i < count; i++) { - result.push(i); - } - - return result; + return inclusiveRange({ min: 0, max: count - 1, step: 1 }); } /**