Skip to content

Commit

Permalink
changed shuffle password algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
thecarlo committed Apr 28, 2024
1 parent 0b67d5a commit 4ebc291
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 8 deletions.
30 changes: 25 additions & 5 deletions src/functions/generate/shufflePassword.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,34 @@
export const shufflePassword = (password: string): string => {
const array = password.split('');

const randomValues = new Uint32Array(array.length);
// Function to check if the shuffled array has consecutive identical elements
const hasConsecutiveDuplicates = (arr: string[]) => {
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] === arr[i + 1]) {
return true;
}
}

crypto.getRandomValues(randomValues);
return false;
};

for (let i = array.length - 1; i > 0; i--) {
const j = randomValues[i] % (i + 1);
// Attempt to shuffle until there are no consecutive duplicates
let shuffled = false;

[array[i], array[j]] = [array[j], array[i]];
while (!shuffled) {
const randomValues = new Uint32Array(array.length);

crypto.getRandomValues(randomValues);

for (let i = array.length - 1; i > 0; i--) {
const j = randomValues[i] % (i + 1);

[array[i], array[j]] = [array[j], array[i]];
}

if (!hasConsecutiveDuplicates(array)) {
shuffled = true;
}
}

return array.join('');
Expand Down
6 changes: 3 additions & 3 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ export default defineConfig({
reportsDirectory: './coverage',
thresholds: {
autoUpdate: true,
statements: 97.81,
branches: 94.84,
statements: 98.11,
branches: 95.14,
functions: 100,
lines: 97.74,
lines: 98.06,
},
},
globals: true,
Expand Down

0 comments on commit 4ebc291

Please # to comment.