Skip to content

Instantly share code, notes, and snippets.

@khalid32
Last active November 28, 2018 05:56
Show Gist options
  • Save khalid32/c55eb9116412b161bea863dfce600d4f to your computer and use it in GitHub Desktop.
Save khalid32/c55eb9116412b161bea863dfce600d4f to your computer and use it in GitHub Desktop.
const createStore = () => {
const tables = {
customer: {
1: {name: 'John'},
2: {name: 'Mattias'},
3: {name: 'Kim'},
},
food: {
1: ['cake', 'waffle'],
2: ['coffee'],
3: ['apple', 'carrot'],
},
};
return{
get: (table, id) => tables[table][id]
};
}
const store = createStore();
const customers = {
[Symbol.iterator]: () => {
let i = 0;
return {
next: () => {
i++;
const customer = store.get('customer', i)
if(!customer) return {done: true}
customer.foods = store.get('food', i);
return {
value: customer,
done: false
}
}
}
}
}
for (const why of customers){
console.log('why ->', why);
}
const array = ['a', 'b', 'c', 'd', 'e'];
const [first, ,third, ,last] = array;
// is similar to this below..
const array = ['a', 'b', 'c', 'd', 'e'];
const iterator = array[Symbol.iterator]();
const first = iterator.next().value
iterator.next().value // Since it was skipped, so it's not assigned
const third = iterator.next().value
iterator.next().value // Since it was skipped, so it's not assigned
const last = iterator.next().value
console.log('%c first: %s, third: %s, last: %s','color: red; font-weight: bold;', first, third, last);
function randomItem(arr){
const randomIndex = {
max: arr.length - 1,
};
const ran = Math.floor(Math.random() * randomIndex.max) + 1;
return arr[ran];
}
// console.log(randomItem(['a', 'b', 'c', 'd', 'e']));
const makeDragon = () => {
const dragonSize = ['big', 'medium', 'tiny', 'mega'];
const dragonAbility = ['fire', 'ice', 'lighting'];
return randomItem(dragonSize) + " " + randomItem(dragonAbility) + " " + 'dragon';
}
// console.log("%c %s", 'color: white; font-weight: bold;', makeDragon());
// using iterator
const dragonArmy = {
[Symbol.iterator]: () => {
return{
next: () => {
const enoughDragonsSpawned = Math.random() > 0.75;
if(!enoughDragonsSpawned)
return{
value: makeDragon(),
done: false,
}
return { done: true }
}
}
}
}
// using generator[syntactic sugar of `iterator`]
const dragonArmy = {
[Symbol.iterator]: function* (){
while(true){
const enoughDragonsSpawned = Math.random() > 0.75;
if(enoughDragonsSpawned) return;
yield makeDragon();
}
}
}
// for(const dragon of dragonArmy){
// console.log("%c %s", 'color: red; font-weight: bold;', dragon);
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment