Skip to content

Instantly share code, notes, and snippets.

@nathan-lapinski
Last active May 20, 2018 13:21
Show Gist options
  • Save nathan-lapinski/0f5f5271e4d3096e8b35ca6ae836fb79 to your computer and use it in GitHub Desktop.
Save nathan-lapinski/0f5f5271e4d3096e8b35ca6ae836fb79 to your computer and use it in GitHub Desktop.
An example of a simple iterator.
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