Skip to content

Instantly share code, notes, and snippets.

@artcommacode
Last active September 27, 2016 11:28
Show Gist options
  • Save artcommacode/ce1fb03202a15fe12a5a93ff10cf622c to your computer and use it in GitHub Desktop.
Save artcommacode/ce1fb03202a15fe12a5a93ff10cf622c to your computer and use it in GitHub Desktop.
// here i'm thinking i needed to use `reduce` twice for some reason
const perms = (str) => {
const words = str.split(' ')
return words.reduce((p, _, i) => {
return p.concat([words.reduce((s, word, j) => {
return j >= i ? s + ` ${word}` : s
}, '').trim()])
}, [])
}
// realising the first fold has simply reproduced `map`
const perms2 = (str) => {
const words = str.split(' ')
return words.map((_, i) => {
return words.reduce((s, word, j) => {
return j >= i ? s + ` ${word}` : s
}, '').trim()
})
}
// and finally realising i didn't need to fold at all
// and could simple `slice` the word array
const perms3 = (str) => {
const words = str.split(' ')
return words.map((_, i) => words.slice(i).join(' '))
}
// and seeing as js gives us the original array as the third argument to `map`
// we can simply even further
const perms4 = (str) => str.split(' ').map((_, i, words) => words.slice(i).join(' '))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment