Skip to content

Instantly share code, notes, and snippets.

@RinatValiullov
Last active December 11, 2017 09:30
Show Gist options
  • Save RinatValiullov/7461bee4d8cb079c9c0940905ec9820c to your computer and use it in GitHub Desktop.
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.
// 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