Skip to content

Commit

Permalink
Make generate random string stronger
Browse files Browse the repository at this point in the history
  • Loading branch information
eleanorreem committed Apr 25, 2023
1 parent 97d9872 commit f20e99a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
14 changes: 14 additions & 0 deletions src/utils/utils.spec.ts
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);
});
});
});
14 changes: 13 additions & 1 deletion src/utils/utils.ts
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));

0 comments on commit f20e99a

Please sign in to comment.