Skip to content

Instantly share code, notes, and snippets.

@vlad-bezden
Last active February 24, 2017 01:58
Show Gist options
  • Save vlad-bezden/584012dafa038b067bc602eb91d62d12 to your computer and use it in GitHub Desktop.
Save vlad-bezden/584012dafa038b067bc602eb91d62d12 to your computer and use it in GitHub Desktop.
Permutations Using Generator Function

Permutations Using Generator Function

// Usage Example: const result = permutations('abc')

for (let value of result) { console.log(value) }

A Pen by Vlad Bezden on CodePen.

License.

'use strict'
function* permutations(data) {
if (data.length < 2) {
yield* data
}
for (let [i, x] of[...data].entries()) {
let rest = data.slice(0, i) + data.slice(i + 1)
for (let j of permutations(rest)) {
yield x + j
}
}
}
const result = permutations('abc')
for (let value of result) {
console.log(value)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment