Skip to content

Commit b9f8e9b

Browse files
add helper function to generate random digits
1 parent 25a31b0 commit b9f8e9b

File tree

3 files changed

+41
-1
lines changed

3 files changed

+41
-1
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "@curiousleaf/utils",
33
"description": "A lightweight set of utilities",
4-
"version": "1.1.2",
4+
"version": "1.1.3",
55
"license": "MIT",
66
"type": "module",
77
"author": {

src/random/random.test.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { describe, expect, it } from "bun:test"
22

33
import {
44
getRandomColor,
5+
getRandomDigits,
56
getRandomElement,
67
getRandomNumber,
78
getRandomProperty,
@@ -64,6 +65,36 @@ describe("getRandomNumber", () => {
6465
})
6566
})
6667

68+
describe("getRandomDigits", () => {
69+
it("returns a string", () => {
70+
const result = getRandomDigits(5)
71+
expect(typeof result).toBe("string")
72+
})
73+
74+
it("returns a string with specified length", () => {
75+
const result = getRandomDigits(10)
76+
expect(result.length).toBe(10)
77+
})
78+
79+
it("returns different strings on each call", () => {
80+
const result1 = getRandomDigits(5)
81+
const result2 = getRandomDigits(5)
82+
expect(result1).not.toBe(result2)
83+
})
84+
85+
it("contains only digits", () => {
86+
const result = getRandomDigits(10)
87+
expect(result).toMatch(/^[0-9]+$/)
88+
})
89+
90+
it("handles different lengths", () => {
91+
const short = getRandomDigits(1)
92+
const long = getRandomDigits(20)
93+
expect(short.length).toBe(1)
94+
expect(long.length).toBe(20)
95+
})
96+
})
97+
6798
describe("getRandomElement", () => {
6899
it("returns a value from the array", () => {
69100
const array = [1, 2, 3]

src/random/random.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,15 @@ export const getRandomNumber = (min: number, max: number) => {
3333
return Math.floor(Math.random() * (max - min + 1)) + min
3434
}
3535

36+
/**
37+
* Generate a random string of digits
38+
* @param length Length of the digits string
39+
* @returns Random digits string
40+
*/
41+
export const getRandomDigits = (length: number) => {
42+
return Array.from({ length }, () => Math.floor(Math.random() * 10)).join("")
43+
}
44+
3645
/**
3746
* Returns a random element from an array.
3847
*

0 commit comments

Comments
 (0)