El-Cortez
El-Cortez

Reputation: 123

Javascript Permutations magic trick

I'm reading some algorithms to try and understand permutations in javascript, and the following one quite stunned me

var permArr = [], usedChars = [];
function permute(input) {
  var i, ch, chars = input.split('');
  for (i = 0; i < chars.length; i++) {
    ch = chars.splice(i, 1);
    usedChars.push(ch);
    if (chars.length == 0) permArr[permArr.length] = usedChars.join('');
    permute(chars.join(""));
    chars.splice(i, 0, ch);
    usedChars.pop();
  }
  return permArr
}

FYI I found this algorithm on the following website: http://staff.roguecc.edu/JMiller/JavaScript/permute.html

I can see that this algorithm works, but there is a line that confuses me and I can't find anywhere where it works

var i, ch, chars = input.split("");

If i console.log(i) or console.log(ch) before OR after in the code, it returns undefined everywhere. If i remove i and ch, the algorithm does not work anymore.

Can someone explain me this line and how it works? Thanks a lot

Upvotes: 1

Views: 137

Answers (1)

nozzleman
nozzleman

Reputation: 9669

No Magic involved

var i, ch, chars = input.split('');

declares the variables i, ch and chars and assigns to chars what input.split('') returns.

Basically its equivalent to

var i; // undefined
var ch; // undefined
var chars = input.split(''); // Array of string

This is typically done for the variables to be available across loop iterations (to access previous values).

However...

i is just the loop varible and could be declared inline as in

for (var i = 0; i < chars.length; i++) {

ch could live inside the loop since it is reassigned in the first statement anyway

  for (var i = 0; i < chars.length; i++) {
      var ch = chars.splice(i, 1);

which makes the example confusing indeed (one could say it's poorly written)

Upvotes: 3

Related Questions