Skip to content

Instantly share code, notes, and snippets.

@attitude
Created March 24, 2018 20:13
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 attitude/c1f6135f785320f4f621d2078d0a9f60 to your computer and use it in GitHub Desktop.
Save attitude/c1f6135f785320f4f621d2078d0a9f60 to your computer and use it in GitHub Desktop.
Generates combinations of strings within array of strings
// @flow
export const stringListCombinationsWithoutSort = (a: string[], transformer: (str: string) => string): string[] => {
return a.reduce((accumulator, propName, i) => [
propName,
...accumulator,
...(accumulator.map((s) => (s + (transformer ? transformer(propName) : propName)))),
], [])
}
export const stringListCombinations = (a: string[], transformer: (str: string) => string): string[] => {
return a.reduce((accumulator, propName, i) => [
...accumulator,
[propName],
...(accumulator.map((s) => ([...s, (transformer ? transformer(propName) : propName)]))),
], [])
.sort((a, b) => a.length === b.length ? 0 : a.length > b.length ? 1 : -1)
.map(a => a.join(''))
}
// const testArray = ['a', 'b', 'c', 'd']
// stringListCombinations(testArray, (s) => (s[0].toUpperCase() + s.slice(1)))
// ["a", "b", "c", "d", "aB", "aC", "bC", "aD", "bD", "cD", "aBC", "aBD", "aCD", "bCD", "aBCD"]
// stringListCombinationsWithoutSort(testArray, (s) => (s[0].toUpperCase() + s.slice(1)))
// ["a", "b", "c", "d", "aB", "aC", "bC", "aD", "bD", "cD", "aBC", "aBD", "aCD", "bCD", "aBCD"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment