shuffle a string in typescript

Here's one way to shuffle a string in TypeScript using the Fisher-Yates shuffle algorithm:

index.ts
function shuffleString(str: string): string {
  const arr = str.split(''); // convert string to array of characters
  for (let i = arr.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [arr[i], arr[j]] = [arr[j], arr[i]]; // swap elements i and j
  }
  return arr.join(''); // convert array back to string
}

const originalString = 'hello world';
const shuffledString = shuffleString(originalString);
console.log(`Original string: ${originalString}`);
console.log(`Shuffled string: ${shuffledString}`);
534 chars
14 lines

The shuffleString function takes a string parameter and returns a shuffled version of that string. It first converts the string to an array of characters using the split method, then performs the Fisher-Yates shuffle algorithm on the array. Finally, it converts the shuffled array back to a string using the join method and returns it.

gistlibby LogSnag