Created
November 27, 2018 22:47
-
-
Save statico/fad9a21325578534a2a5c1b937717db5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] | |
]) | |
}) | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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