From 4ebc291f414b543e3b162094d47207c7abb85fb8 Mon Sep 17 00:00:00 2001 From: Carlo van Wyk <5310264+thecarlo@users.noreply.github.com> Date: Sun, 28 Apr 2024 17:33:44 +1000 Subject: [PATCH] changed shuffle password algorithm --- src/functions/generate/shufflePassword.ts | 30 +++++++++++++++++++---- vite.config.ts | 6 ++--- 2 files changed, 28 insertions(+), 8 deletions(-) diff --git a/src/functions/generate/shufflePassword.ts b/src/functions/generate/shufflePassword.ts index 4caac2b..5a9b2d1 100644 --- a/src/functions/generate/shufflePassword.ts +++ b/src/functions/generate/shufflePassword.ts @@ -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(''); diff --git a/vite.config.ts b/vite.config.ts index a3ac801..857cfc1 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -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,