Last active
August 26, 2015 18:32
-
-
Save KasaiMagi/07e279d71556ecac9694 to your computer and use it in GitHub Desktop.
Generator vs Closure example
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
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()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
can be
or all in one line:
;)