# Please explain Heap's algorithm step by step in this recursive javascript code.

function permuteAll(str) { var arr = str.split(''); var n = arr.length; var result = []; perm(arr,n); return result; function perm(s,length) { if( length === 1) { result.push(s.join('')); } for(var i=0;i<length; i++) { perm(s,length-1); if(length%2 !== 0) { swap(s,0,length-1); } else if(length%2 === 0) { swap(s,i,length-1); } } } function swap(array,x,y){ var tmp = array[x]; array[x] =array[y]; array[y] = tmp; } } console.log(permuteAll('123')); Can someone please explain to me step by step how does this unbelievable piece of code can output all permutations of the input string. I already know what recursion is but only on the basic level. Like the basic factorial recursive solution. I can't seem to grasp how the push call will be called n! times. I already read the Wikipedia article, stackoverflow threads but still don't get it. Thanks.