Created
November 24, 2020 06:55
-
-
Save whal-e3/e97383691d2c4c81c776a6713d33ac76 to your computer and use it in GitHub Desktop.
JS Iterator/Generator - real use (dating website)
This file contains hidden or 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 data = [ | |
{ | |
name: 'John Doe', | |
age: 32, | |
gender: 'male', | |
lookingfor: 'female', | |
location: 'Boston MA', | |
image: 'https://randomuser.me/api/portraits/men/82.jpg' | |
}, | |
{ | |
name: 'Jen Smith', | |
age: 26, | |
gender: 'female', | |
lookingfor: 'male', | |
location: 'Miami FL', | |
image: 'https://randomuser.me/api/portraits/women/82.jpg' | |
}, | |
{ | |
name: 'William Johnson', | |
age: 38, | |
gender: 'male', | |
lookingfor: 'female', | |
location: 'Lynn MA', | |
image: 'https://randomuser.me/api/portraits/men/83.jpg' | |
} | |
]; | |
// ------------------------------------------------ | |
const profiles = profileIterator(data); | |
// Call first profile | |
nextProfile(); | |
document.getElementById('next').addEventListener('click', nextProfile); | |
function nextProfile() { | |
const currentProfile = profiles.next().value; | |
if (currentProfile !== undefined) { | |
document.getElementById('profileDisplay').innerHTML = ` | |
<ul class='list-group'> | |
<li class='list-group-item'>Name: ${currentProfile.name}</li> | |
<li class='list-group-item'>Age: ${currentProfile.age}</li> | |
<li class='list-group-item'>Location: ${currentProfile.location}</li> | |
<li class='list-group-item'>Preference: ${currentProfile.gender} looking for ${currentProfile.lookingfor}</li> | |
</ul> | |
`; | |
document.getElementById( | |
'imageDisplay' | |
).innerHTML = `<img src="${currentProfile.image}">`; | |
} else { | |
// NO more profiles | |
window.location.reload(); | |
} | |
} | |
// Profile Iterator | |
function profileIterator(profiles) { | |
let nextIndex = 0; | |
return { | |
next: function () { | |
return nextIndex < profiles.length | |
? { value: profiles[nextIndex++], done: false } | |
: { done: true }; | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment