Skip to main content
1 of 4
Blindman67
  • 22.3k
  • 2
  • 16
  • 40

Typed arrays for better performance.

Using the accepted answers method you can triple the performance.

Running the winning answer on my machine gave benchmarked

Mean : 5,564,999µs ±182,246µs 11 samples

And when using typed arrays

Mean : 1,514,112µs ±72,000µs (*) 13 samples

for 3.68 performance increase.

var knownPermutations = [0,0,0,24,120,720,5040,40320,362880,3628800];
function anagramer(input) {
    var counter, chars,length,i,index,tc,n,arraySize,anagrams;
    index = 0;
    length = input.length;
    arraySize = knownPermutations[length-1] * length;
    anagrams = new Uint8Array(arraySize);
    chars = new Uint8Array(length);
    counter = new Uint8Array(length);
    for( i = 0; i < length; i ++){
        chars[i] = input.charCodeAt(i);
    }
    

    anagrams.set(chars)
    index += length;
    i = 0;
    while (i < length) {
        if (counter[i] < i) {
            tc = chars[i];
            chars[i] = chars[n= (i%2?counter[i]:0)];
            chars[n] = tc;
            counter[i]++;
            i = 0;
            anagrams.set(chars,index)
            index += length;
        } else {
            counter[i] = 0;
            i++;
        }
    }
    return anagrams;
}      

To edge a little more you can predefine the result array to get

 Mean : 1,408,974µs ±25,173µs (*) 24 samples

To improve it up to 3.95 times as quick as the winning answer.

Blindman67
  • 22.3k
  • 2
  • 16
  • 40