Last active
December 11, 2017 09:30
-
-
Save RinatValiullov/7461bee4d8cb079c9c0940905ec9820c to your computer and use it in GitHub Desktop.
Instead of generators in ES6(Douglas Crockford's pattern). Returns next element of the array each time when generator inner function invokes.
This file contains hidden or 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
// Simple array | |
const myArray = [4,5,6]; | |
const factoryFunction = (array) => { | |
// The generator's state variable(s) | |
let i = 0; | |
return function generator() { | |
if(i < array.length) { | |
// Compute the new value | |
let value = array[i]; | |
// Update the state variable(s) | |
i += 1; | |
return value; | |
} | |
} | |
}; | |
const newInstance = factoryFunction(myArray); | |
newInstance(); // 4 | |
newInstance(); // 5 | |
newInstance(); // 6 | |
newInstance(); // undefined |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment