title: Javascript Heap's algorithm (non-recursive)
body: <p>I have implemented Heap's non-recursive algorithm in JavaScript.
  When checking permutations with <code>console.log(arr)</code> everything works as expected. 
  But when I try to push each permutation to a result array, then everything breaks up. It just returns result filled with last iteration permutation. 
  <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function generate(n, arr) {
   function swap(item1, item2){
    console.log(item1, item2);
    let tmp = arr[item1];
    arr[item1] = arr[item2];
    arr[item2] = tmp;
   }
   var c = [];
   var allPermutations = [];
   
   for (let i = 0; i &lt; n; i++) {
    c[i] = 0;
   }
   
   console.log(arr);
   allPermutations.push(arr);
   
   for (let i = 1; i &lt; n; i) {
    if (c[i] &lt; i) {
     if (i % 2 == 0) {
      swap(0, i);
     } else {
      swap(c[i], i);
     }
     
     console.log(arr);
     allPermutations.push(arr);
     
     c[i] += 1;
     i = 1;
    } else {
     c[i] = 0;
     i += 1;
    }
   }
   
   return allPermutations;
  }
  
  console.log('result', generate(3, ["a", "a", "b"]));</code></pre>
  </div>
  </div>
  </p>