Skip to content

Commit

Permalink
feat: adds randomFloatBetween
Browse files Browse the repository at this point in the history
  • Loading branch information
pleb committed Jun 29, 2022
1 parent 288f853 commit ab87f44
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/data-utilties.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ export function randomNumberBetween(min: number, max: number): number {
return Math.floor(Math.random() * (max - min + 1) + min)
}

export function randomFloatBetween(min: number, max: number, decimals?: number) {
const float = Math.random() * (max - min) + min
return decimals ? parseFloat(float.toFixed(decimals)) : float
}

/**
* Generates a random string with a length between `min` and `max`
*
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export {
randomDate,
randomDateBetween,
randomNumberBetween,
randomFloatBetween,
randomNumber,
incrementedNumber,
randomId,
Expand Down
15 changes: 15 additions & 0 deletions test/data-utilities.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
randomDateRangeMin,
randomElement,
randomEmail,
randomFloatBetween,
randomId,
randomNumber,
randomNumberBetween,
Expand All @@ -32,6 +33,20 @@ describe('Data utilities', () => {
expect(sut).toBeLessThanOrEqual(10)
})
})
describe('randomFloatBetween', () => {
it('generates a random float between two inputs', () => {
for (let i = 1; i < 99; i++) {
const decimalPlaces = randomNumberBetween(1, 20)

const sut = randomFloatBetween(0, i, decimalPlaces)
const decimals = sut.toLocaleString('en-au').split('.')

if (decimals.length === 2) expect(sut.toLocaleString('en-au').split('.')[1].length).toBeLessThanOrEqual(decimalPlaces)
expect(sut).toBeGreaterThanOrEqual(0)
expect(sut).toBeLessThanOrEqual(i)
}
})
})
describe('randomString', () => {
it('generates a random string with the length between the two inputs', () => {
const sut = randomString(10, 20)
Expand Down

0 comments on commit ab87f44

Please sign in to comment.