Skip to content

Commit

Permalink
Improve pwd creation code and unit testing
Browse files Browse the repository at this point in the history
  • Loading branch information
thomaschampagne committed Jan 24, 2024
1 parent 52abba0 commit eb99be3
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 9 deletions.
10 changes: 1 addition & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,8 @@ export class Sesame {
*/
public static create(length: number): string {
const availableChars = Sesame.AVAILABLE_CHARS;
const randomChars = new Array(length);
const cryptoArray = new Uint32Array(length);

crypto.getRandomValues(cryptoArray);

for (let i = 0; i < length; i++) {
const randomIndex = cryptoArray[i] % availableChars.length;
randomChars[i] = availableChars.charAt(randomIndex);
}

return randomChars.join('');
return Array.from(cryptoArray, num => availableChars.charAt(num % availableChars.length)).join('');
}
}
29 changes: 29 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,33 @@ describe('Sesame', () => {
// Then
expect(password.length).toEqual(expectedLength);
});

it('should return a string of the specified length', () => {
// Given a specified length
const length = 10;
// When the password is created
const password = Sesame.create(length);
// Then the password should have the specified length
expect(password).to.have.lengthOf(length);
});

it('should only contain characters from the available characters', () => {
// Given a password of length 100
const password = Sesame.create(100);
const availableChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*{}(),.;:/<>?|_-+=';
// When we check each character in the password
for (const char of password) {
// Then each character should be in the list of available characters
expect(availableChars).to.include(char);
}
});

it('should generate different passwords each time', () => {
// Given two passwords of equal length
const password1 = Sesame.create(10);
const password2 = Sesame.create(10);
// When we compare the two passwords
// Then they should not be equal
expect(password1).to.not.equal(password2);
});
});

0 comments on commit eb99be3

Please sign in to comment.