Skip to content

Instantly share code, notes, and snippets.

@KasaiMagi
Last active August 26, 2015 18:32
Show Gist options
  • Save KasaiMagi/07e279d71556ecac9694 to your computer and use it in GitHub Desktop.
Save KasaiMagi/07e279d71556ecac9694 to your computer and use it in GitHub Desktop.
Generator vs Closure example
function* genColor() {
const colors = ['#5cb8d6', '#79d4f2', '#ffc425', '#f2dd6a', '#4ac327', '#87db42', '#ef9520', '#f6c452', '#41c3c0', '#65e1dd', '#6ca1b6', '#8cc1d7', '#16bb93', '#44debb']
let index = 0
while(true) {
yield colors[index]
index++
if (index >= colors.length) {
index = 0
}
}
}
var getColor = genColor()
console.log(getColor.next().value)
console.log(getColor.next().value)
console.log(getColor.next().value)
console.log(getColor.next().value)
console.log(getColor.next().value)
function closeColor() {
const colors = ['#5cb8d6', '#79d4f2', '#ffc425', '#f2dd6a', '#4ac327', '#87db42', '#ef9520', '#f6c452', '#41c3c0', '#65e1dd', '#6ca1b6', '#8cc1d7', '#16bb93', '#44debb']
let index = 0
return function() {
let color = colors[index]
index++
if (index >= colors.length) {
index = 0
}
return color
}
}
var getColor = closeColor()
console.log(getColor())
console.log(getColor())
console.log(getColor())
console.log(getColor())
console.log(getColor())
@petrbela
Copy link

    index++

    if (index >= colors.length) {
      index = 0
    }

can be

index = ++index % colors.length

or all in one line:

return colors[index++ % colors.length]

;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment