Generate all possible combinations of letters in a word This is a JavaScript function that returns ALL the possible combinations of whatever word the user enters. I am looking to clean this code up a bit...any and all suggestions are welcome!

  function allAnagrams (word) {
  if (word.length &lt; 2) {
    return [word];
  } else {
      var allAnswers = [];
      for (var i = 0; i &lt; word.length; i++) {
        var letter = word[i];
        var shorterWord = word.substr(0, i) + word.substr(i + 1, word.length - 1);
        var shortwordArray = allAnagrams(shorterWord);
        for (var j = 0; j &lt; shortwordArray.length; j++) {
          allAnswers.push(letter + shortwordArray[j]);
        }
      }
      return allAnswers;
  }
}

allAnagrams("")
I'm going to throw my hat in the ring with the iterative version of Heap's method of generating permutations. It took me a while to get right, as my reference source has a typo in the algorithm -_-.

function swap(chars, i, j) {
    var tmp = chars[i];
    chars[i] = chars[j];
    chars[j] = tmp;
}

function getAnagrams(input) {
    var counter = [],
        anagrams = [],
        chars = input.split(''),
        length = chars.length,
        i;

    for (i = 0; i &lt; length; i++) {
        counter[i] = 0;
    }

    anagrams.push(input);
    i = 0;
    while (i &lt; length) {
        if (counter[i] &lt; i) {
            swap(chars, i % 2 === 1 ? counter[i] : 0, i);
            counter[i]++;
            i = 0;
            anagrams.push(chars.join(''));
        } else {
            counter[i] = 0;
            i++;
        }
    }

    return anagrams;
}


With some sample timings to count the anagrams of "codereview":


$ time node anagrams-heap-iterative.js
3628800

real    0m0.855s
user    0m0.000s
sys     0m0.015s

$ time node anagrams-megawac.js
3628800

real    0m2.286s
user    0m0.000s
sys     0m0.000s