✨(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:
committed by
aleb_the_flash
parent
60ff04c2d9
commit
f967775fb6
37
packages/react/src/utils/index.spec.tsx
Normal file
37
packages/react/src/utils/index.spec.tsx
Normal 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."
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -12,3 +12,9 @@ export function randomString(length: number = 8): string {
|
|||||||
result += chars[Math.floor(Math.random() * chars.length)];
|
result += chars[Math.floor(Math.random() * chars.length)];
|
||||||
return result;
|
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);
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user