Skip to content

Instantly share code, notes, and snippets.

@py-in-the-sky
Last active August 29, 2015 14:28
Show Gist options
  • Save py-in-the-sky/c55aec90e9883c68fdf3 to your computer and use it in GitHub Desktop.
Save py-in-the-sky/c55aec90e9883c68fdf3 to your computer and use it in GitHub Desktop.
Recursive Generator Function in JavaScript
// Works in Chrome devtools console
function* downToZero (n) {
yield n; // yield "first" element of the "list"
if (n > 0) // yield each element of the "rest" of the "list"
for (var n2 of downToZero(n - 1))
yield n2;
}
var tenToZero = downToZero(10);
console.log('The first number should be 10:', tenToZero.next().value);
console.log('The second number should be 9:', tenToZero.next().value);
console.log('The third number should be 8:', tenToZero.next().value);
console.log('The for-loop below should take off from 7')
for (var number of tenToZero)
console.log(number);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment