I am trying to write a code to create permutations of a string. This is my code:
function perm(str){
function addNew(arr,char){
    var result =[];
    for(i=0;i<=arr.length;i++){
      var temp =[...arr];
      temp.splice(i,0,char);
      result.push(temp);
    }
    return result;
  }
  var chars =str.split("");
  var results =[[]];
  for(i=0;i<chars.length;i++){
   var temp =[...results];
   results =[];
   for(j=0;j<temp.length;j++){
     results =[...results,...addNew(temp[j],chars[i])];
   } 
  }
  return results;
}  
perm("abcd")
This returns:
[ [ 'd', 'c', 'a' ],
  [ 'c', 'd', 'a' ],
  [ 'c', 'a', 'd' ],
  [ 'd', 'a', 'c' ],
  [ 'a', 'd', 'c' ],
  [ 'a', 'c', 'd' ] ]
perm(acde) returns:
[ [ 'e', 'd', 'a' ],
  [ 'd', 'e', 'a' ],
  [ 'd', 'a', 'e' ],
  [ 'e', 'a', 'd' ],
  [ 'a', 'e', 'd' ],
  [ 'a', 'd', 'e' ] ]
So, basically the loop is skipping over (only)the second character in the string. Can someone explain why?
P.S. I know the algorithm is pretty inefficient for the problem but I am just starting with coding, and yet to completely understand Heap's algorithm. I am very curious about this behavior though, and would be pretty thankful if someone would explain.
