The source code is re-edited to be runnable as self-contained code snippets, ebeneven though in the literature it is common to see algorithms with "globals".
function permute(N) {
function swap(x, y) { [ P[x], P[y] ] = [ P[y], P[x] ] }
function heap(n, i) { return (n % 2) || i }
var P = []; for (let i = 1; i <= N; i++) P[i] = i;
var count = 1;
console.log(count++, ":", P.slice(1));
for (p of permutations(N)) console.log(count++, ":", p.slice(1));
function* permutations(n) {
if (n > 1) {
for (let i = 1; i <= n; i++) {
yield* permutations(n - 1);
if (i < n) { swap(n, heap(n, i)); yield P }
}
}
}
}
permute(4);