function k_combinations(set, k) { var i, j, combs, head, tailcombs; if (k > set.length || k <= 0) { return []; } if (k == set.length) { return [set]; } if (k == 1) { combs = []; for (i = 0; i < set.length; i++) { combs.push([set[i]]); } return combs; } combs = []; for (i = 0; i < set.length - k + 1; i++) { // head is a list that includes only our current element. head = set.slice(i, i + 1); // We take smaller combinations from the subsequent elements tailcombs = k_combinations(set.slice(i + 1), k - 1); // For each (k-1)-combination we join it with the current // and store it to the set of k-combinations. for (j = 0; j < tailcombs.length; j++) { combs.push(head.concat(tailcombs[j])); } } return combs; } function stringPermutations(str) { let letters = str.split('') , results = [[letters.shift()]] while (letters.length) { const currLetter = letters.shift() let tmpResults = [] results.forEach(result => { let rIdx = 0 while (rIdx <= result.length) { const tmp = [...result] tmp.splice(rIdx, 0, currLetter) tmpResults.push(tmp) rIdx++ } }) results = tmpResults } return results .map(letterArray => letterArray.join('')) .filter((el, idx, self) => (self.indexOf(el) === idx)) .sort() } export function calculateCombination(text, n) { return k_combinations(text.split(''), n).map(it => stringPermutations(it.join(''))).flat().filter((value, index, self) => { return self.indexOf(value) === index; }); }