From f967775fb662c63a00da567fefd9ae4771b351f7 Mon Sep 17 00:00:00 2001 From: Lebaud Antoine Date: Mon, 22 May 2023 16:40:49 +0200 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8(react)=20compute=20a=20range=20of=20n?= =?UTF-8?q?umbers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A new utils function has been added that would allow developpers to easily compute a range between two number, with a step of one. This function is inspired by the python range function. --- packages/react/src/utils/index.spec.tsx | 37 +++++++++++++++++++++++++ packages/react/src/utils/index.ts | 6 ++++ 2 files changed, 43 insertions(+) create mode 100644 packages/react/src/utils/index.spec.tsx diff --git a/packages/react/src/utils/index.spec.tsx b/packages/react/src/utils/index.spec.tsx new file mode 100644 index 0000000..063fb5f --- /dev/null +++ b/packages/react/src/utils/index.spec.tsx @@ -0,0 +1,37 @@ +import { expect } from "vitest"; +import { range } from ":/utils/index"; + +describe("range", () => { + it.each([ + [-10, 10], + [-10, -10], + [10, 20], + [1, 5], + [1, 1], + [10, 10], + ])("returns a range of number", async (min, max) => { + const output = range(min, max); + // Check length of the range. + expect(output.length).eq(max - min + 1); + + // Check first and last value. + expect(output[0]).eq(min); + expect(output.slice(-1)[0]).eq(max); + + // Check step between values. + output.forEach( + (item, index) => + index < output.length - 1 && expect(output[index + 1] - item).eq(1) + ); + }); + + it.each([ + [-30, -40], + [10, 5], + [10, 0], + ])("raises error if max is inferior to min", async (min, max) => { + expect(() => range(min, max)).toThrow( + "`min` arg must be inferior to `max` arg." + ); + }); +}); diff --git a/packages/react/src/utils/index.ts b/packages/react/src/utils/index.ts index 63e217b..bdebe64 100644 --- a/packages/react/src/utils/index.ts +++ b/packages/react/src/utils/index.ts @@ -12,3 +12,9 @@ export function randomString(length: number = 8): string { result += chars[Math.floor(Math.random() * chars.length)]; return result; } +export function range(min: number, max: number): Array { + if (max < min) { + throw new Error("`min` arg must be inferior to `max` arg."); + } + return Array.from({ length: max - min + 1 }, (_, i) => i + min); +}