find all possible combinations of letters javascript

Solutions on MaxInterview for find all possible combinations of letters javascript by the best coders in the world

showing results for - "find all possible combinations of letters javascript"
Nicolò
01 May 2019
1// read the question from stackexchange for more details
2// https://codereview.stackexchange.com/questions/57161/generate-all-possible-combinations-of-letters-in-a-word
3
4function swap(chars, i, j) {
5    var tmp = chars[i];
6    chars[i] = chars[j];
7    chars[j] = tmp;
8}
9
10function getAnagrams(input) {
11    var counter = [],
12        anagrams = [],
13        chars = input.split(''),
14        length = chars.length,
15        i;
16
17    for (i = 0; i < length; i++) {
18        counter[i] = 0;
19    }
20
21    anagrams.push(input);
22    i = 0;
23    while (i < length) {
24        if (counter[i] < i) {
25            swap(chars, i % 2 === 1 ? counter[i] : 0, i);
26            counter[i]++;
27            i = 0;
28            anagrams.push(chars.join(''));
29        } else {
30            counter[i] = 0;
31            i++;
32        }
33    }
34
35    return anagrams;
36}
37