(react) compute a range of numbers

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.
This commit is contained in:
Lebaud Antoine
2023-05-22 16:40:49 +02:00
committed by aleb_the_flash
parent 60ff04c2d9
commit f967775fb6
2 changed files with 43 additions and 0 deletions

View File

@@ -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."
);
});
});

View File

@@ -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<number> {
if (max < min) {
throw new Error("`min` arg must be inferior to `max` arg.");
}
return Array.from({ length: max - min + 1 }, (_, i) => i + min);
}