Last active
May 20, 2018 13:21
-
-
Save nathan-lapinski/0f5f5271e4d3096e8b35ca6ae836fb79 to your computer and use it in GitHub Desktop.
An example of a simple iterator.
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
const megamanBosses = { | |
[Symbol.iterator]: () => { | |
return { | |
next: () => { | |
const stop = Math.random() > 0.85; | |
if (!stop) { | |
return { | |
value: megaManNameCreator(), | |
done: false | |
}; | |
} else { | |
return { | |
value: undefined, | |
done: true | |
}; | |
} | |
} | |
}; | |
} | |
}; | |
// helper function for generating Mega Man boss names | |
const megaManNameCreator = () => { | |
const abilities = [ | |
'Fire', | |
'Ice', | |
'Wind', | |
'Metal', | |
'Blade', | |
'Storm', | |
'Thunder', | |
'Blast', | |
'Kinetic', | |
'Snow' | |
]; | |
const randomIndex = Math.floor(Math.random() * (abilities.length)); | |
return abilities[randomIndex] + ' Man'; | |
} | |
// consume it via for..of: | |
for (const boss of megamanBosses) { | |
console.log('iterated: ', boss); | |
} | |
// or array destructuring | |
const [a, b, c] = megamanBosses; | |
// or using spread | |
const bosses = [...megamanBosses]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment