Skip to content

Instantly share code, notes, and snippets.

@tudormunteanu
Created July 27, 2022 09:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tudormunteanu/29a82c848b434f5eb1cde5bb2eb64252 to your computer and use it in GitHub Desktop.
Save tudormunteanu/29a82c848b434f5eb1cde5bb2eb64252 to your computer and use it in GitHub Desktop.
Combinations of strings up to a certain number of elements
export default function combinations(items: Array<string>, items_length: number, n: number): Array<string> {
const result = [];
const getCombinations = (x, n, m = []) => {
if (n <= 0) {
return m
}
for (var i = 0; i < items_length; i++) {
const value = getCombinations(x, n - 1, [...m, items[i]]);
const hasDuplicates = (arr) => arr.length !== new Set(arr).size;
if (!hasDuplicates(value)) {
result.push(value);
}
}
return m;
}
getCombinations(items.length, n);
return result.filter(items => items.length == n);
}
import combinations from '@/utils/combinations';
SEO_TERMS = ["a", "b", "c", "d", "e"]
combinations(SEO_TERMS, SEO_TERMS.length, 1)
combinations(SEO_TERMS, SEO_TERMS.length, 2)
combinations(SEO_TERMS, SEO_TERMS.length, 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment