Build a Permutation Generator - Build a Permutation Generator

The result for “walk” is now:

[ 'walk',
  'wakl',
  'wla',
  'wkal',
  'wkla',
  'aw',
  'lwa',
  'law',
  'kwal',
  'kwla',
  'kaw',
  'klwa',
  'klaw' ]

Can I simply filter this result to remove the options that have less than 4 characters, or is there an underlying logic error?

This is my code now:

function permuteString(string, prefix = "", results = []) {
  if (string.length === 0) {
    results.push(prefix);
    prefix = "";
    return results;
  };
  for (let character in string) {
    let newString = string.substring(0, character) + string.substring(character + 1,);
    permuteString(newString, prefix + string[character], results);
  };
  return results;
}

if it’s doing that something is not working, they should all have the same lenght

when character is 2
this is loosing one letter:

    let newString = string.substring(0, character) + string.substring(character + 1,);

it should get wak, with the third letter l going to prefix, instead
string.substring(0, '2') is wa and string.substring(character + 1,); is an empty string

unfortunately, character + 1 or '2' + 1 is equal to 21

This outputs ‘wak’- is that not what is intended? I’m fairly sure that’s what the code id doing in the example you just gave.

console.log("walk".substring(0, 2) + "walk".substring(3,));

unfortunately character + 1, or '2' + 1 does not make three, it makes '21', because using + with a string is concatenation

you need to do something slightly differently to get 3

being fairly sure is not enough, it makes you wrong. Test it. Open the browser console and test

the explanation above that it makes '21' comes from me testing, you can verify running your code

why is character a string? It’s the index of the character in the string

that’s what a for…in loop does, it gives you strings