-
Notifications
You must be signed in to change notification settings - Fork 27
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Make generate random string stronger
- Loading branch information
1 parent
97d9872
commit f20e99a
Showing
2 changed files
with
27 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
import { generateRandomString } from './utils'; | ||
|
||
describe('Utils', () => { | ||
describe('generateRandomString', () => { | ||
it('should create string of length 10', () => { | ||
const randomString = generateRandomString(10); | ||
expect(randomString.length).toBe(10); | ||
}); | ||
it('should create string of the correct length 2', () => { | ||
const randomString = generateRandomString(2); | ||
expect(randomString.length).toBe(2); | ||
}); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,17 @@ | ||
import { webcrypto } from 'crypto'; | ||
const crypto = webcrypto as unknown as Crypto; | ||
|
||
export const generateRandomString = (length: number) => { | ||
return [...Array(length)].map(() => (~~(Math.random() * 36)).toString(36)).join(''); | ||
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; | ||
const charactersLength = characters.length; | ||
const randomValues = new Uint32Array(length); | ||
const cryptoedValues = crypto.getRandomValues(randomValues); | ||
|
||
return [...cryptoedValues] | ||
.map((val) => { | ||
return characters.charAt(val % charactersLength); | ||
}) | ||
.join(''); | ||
}; | ||
|
||
export const getYesterdaysDate = () => new Date(new Date().setDate(new Date().getDate() - 1)); |