0

I tried shuffling a string with a fisher-yates shuffle, but although it properly gets the indexes and the values, it doesn't shuffle the string, what is wrong?

globalVar = 'I am GLOBAL'

function scrambler(anyString) {
  let placeHolder = anyString
  for (let i = placeHolder.length - 1; i >= 0; i--) {
    let swapIndex = Math.floor(Math.random() * (i + 1))
    let chartoSwap = placeHolder[swapIndex]
    let currentChar = placeHolder[i]
    placeHolder[i] = chartoSwap
    placeHolder[swapIndex] = currentChar
  }
  return placeHolder
}

let scrambled = scrambler(globalVar)
console.log(scrambled)
Taki
  • 17,320
  • 4
  • 26
  • 47
JCaptain
  • 57
  • 4
  • 1
    Have you tried debugging it? If you say it gets the indexes and values correctly, then what did you do to see what happens AFTER that? You may want to look up "[javascript](https://developer.mozilla.org/en-US/docs/Glossary/Mutable) [string](https://en.wikipedia.org/wiki/Immutable_object) [immutability](https://www.sitepoint.com/immutability-javascript/)". – RobIII Sep 24 '19 at 19:31

2 Answers2

4

strings are immutable. Change placeHolder into an array

globalVar = 'I am GLOBAL'

function scrambler(anyString) {
  let placeHolder = anyString.split("")
  for (let i = placeHolder.length - 1; i >= 0; i--) {
    let swapIndex = Math.floor(Math.random() * (i + 1))
    let chartoSwap = placeHolder[swapIndex]
    let currentChar = placeHolder[i]
    placeHolder[i] = chartoSwap
    placeHolder[swapIndex] = currentChar
  }
  return placeHolder.join("")
}

let scrambled = scrambler(globalVar)
console.log(scrambled)
marzelin
  • 10,790
  • 2
  • 30
  • 49
1

Strings are immutable and you cannot mutate them. Read this for more information: https://stackoverflow.com/a/1431113/1128441

String.prototype.replaceAt=function(index, replacement) {
  return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}
ChrisG
  • 2,637
  • 18
  • 20