DEV Community

Sh Raj
Sh Raj

Posted on • Edited on

Creating a Custom JavaScript Function to Shuffle Strings with a Key Parameter

function shuffleString(text, key) {
  const array = text.split('');
  let seed = key;
  const random = () => {
    const x = Math.sin(seed++) * 10000;
    return x - Math.floor(x);
  };

  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }

  return array.join('');
}

Enter fullscreen mode Exit fullscreen mode
// Example usage:
const text = '123456';
const key = 20;

const shuffledText = shuffleString(text, key);
console.log(shuffledText); // Output: '231465'

const shuffledTextAgain = shuffleString(text, key);
console.log(shuffledTextAgain); // Output: '231465'

Enter fullscreen mode Exit fullscreen mode

The shuffleString function takes two parameters: text, which is the input string to be shuffled, and key, which is a numeric value used to determine the shuffling order.

The function uses the Fisher-Yates algorithm to shuffle the characters in the text string. The shuffling is based on a custom pseudo-random number generator that is seeded with the provided key value.

Here's a step-by-step explanation of how the shuffleString function works:

  1. The input text is split into an array of individual characters.
  2. The key value is used to initialize a seed for the pseudo-random number generator.
  3. The random function is defined within the shuffleString function. It generates pseudo-random values between 0 and 1 using a custom implementation based on the sine function and the incremented seed value.
  4. The Fisher-Yates algorithm is used to iterate over the array of characters from the last element to the first.
  5. For each iteration, a random index j is generated using the random function. The index j is a random integer between 0 and the current index i.
  6. The character at index i and the character at index j are swapped using destructuring assignment: [array[i], array[j]] = [array[j], array[i]].
  7. After all iterations are complete, the shuffled array of characters is joined back into a string.
  8. The shuffled string is returned as the output of the shuffleString function.

By providing a specific key value, you can consistently reproduce the same shuffling order for the same input text. The shuffled output will be different for different key values.

I hope this clarifies how the shuffleString function works. Let me know if you have any further questions!

Top comments (0)