Skip to content

Instantly share code, notes, and snippets.

@statico
Created November 27, 2018 22:47
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 statico/fad9a21325578534a2a5c1b937717db5 to your computer and use it in GitHub Desktop.
Save statico/fad9a21325578534a2a5c1b937717db5 to your computer and use it in GitHub Desktop.
import permutations from '../permutations'
describe('the permutation function', () => {
it('should handle the empty array case', () => {
expect(Array.from(permutations([]))).toEqual([])
})
it('should handle the a single element', () => {
expect(Array.from(permutations([['a']]))).toEqual([['a']])
expect(Array.from(permutations([['a', 'b', 'c']]))).toEqual([['a'], ['b'], ['c']])
})
it('should handle multiple elements', () => {
expect(Array.from(permutations([['a', 'b', 'c'], [1, 2, 3]]))).toEqual([
['a', 1],
['a', 2],
['a', 3],
['b', 1],
['b', 2],
['b', 3],
['c', 1],
['c', 2],
['c', 3]
])
})
})
export default function* permutations(items: any[][], index: number = 0, ret?: any[]) {
if (index >= items.length) {
if (ret) {
yield ret
}
} else {
const next = ret || []
for (const item of items[index]) {
yield* permutations(items, index + 1, next.concat(item))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment