Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .test-summary/TEST_SUMMARY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
## Test Summary

**Mentors**: For more information on how to review homework assignments, please refer to the [Review Guide](https://github.com/HackYourFuture/mentors/blob/main/assignment-support/review-guide.md).

### 3-UsingAPIs - Week2

| Exercise | Passed | Failed | ESLint |
|-------------------|--------|--------|--------|
| ex1-programmerFun | 2 | 3 | ✓ |
| ex2-pokemonApp | 5 | - | ✓ |
| ex3-rollAnAce | 6 | 1 | ✓ |
| ex4-diceRace | 7 | - | ✓ |
| ex5-vscDebug | - | - | ✓ |
| ex6-browserDebug | - | - | ✓ |
3 changes: 3 additions & 0 deletions 3-UsingAPIs/Week2/assignment/.vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"liveServer.settings.port": 5501
}
48 changes: 31 additions & 17 deletions 3-UsingAPIs/Week2/assignment/ex1-programmerFun/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,29 +16,43 @@ Full description at: https://github.com/HackYourFuture/Assignments/blob/main/3-U
url with `.shx`. There is no server at the modified url, therefore this
should result in a network (DNS) error.
------------------------------------------------------------------------------*/
function requestData(url) {
// TODO return a promise using `fetch()`
}
async function requestData(url) {
try {
const response = await fetch(url);

if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}

const data = await response.json();
return data;
} catch (error) {
throw error;
}
}
// Function to render image
function renderImage(data) {
// TODO render the image to the DOM
const img = document.createElement('img');
img.src = data.img;
document.body.appendChild(img);
console.log(data);
}

// Function to render errors
function renderError(error) {
// TODO render the error to the DOM
const h1 = document.createElement('h1');
h1.textContent = error.message || error;
document.body.appendChild(h1);
console.log(error);
}
// Refactored main function to use async/await
async function main() {
try{
const data = await requestData('https://xkcd.now.sh/?comic=latest');
renderImage(data);
} catch (error) {
renderError(error);
}
}

// TODO refactor with async/await and try/catch
function main() {
requestData('https://xkcd.now.sh/?comic=latest')
.then((data) => {
renderImage(data);
})
.catch((error) => {
renderError(error);
});
}

window.addEventListener('load', main);
window.addEventListener('load', main); window.addEventListener('load', main);
74 changes: 66 additions & 8 deletions 3-UsingAPIs/Week2/assignment/ex2-pokemonApp/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,76 @@ Use async/await and try/catch to handle promises.
Try and avoid using global variables. As much as possible, try and use function
parameters and return values to pass data back and forth.
------------------------------------------------------------------------------*/
function fetchData(/* TODO parameter(s) go here */) {
// TODO complete this function
async function fetchData(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Fetch error:', error);
throw error;
}
}

function fetchAndPopulatePokemons(/* TODO parameter(s) go here */) {
// TODO complete this function
}
async function fetchAndPopulatePokemons() {
const url = 'https://pokeapi.co/api/v2/pokemon?limit=150';
try {
const data = await fetchData(url);
const select = document.querySelector('select');
select.innerHTML = '';

function fetchImage(/* TODO parameter(s) go here */) {
// TODO complete this function
data.results.forEach((pokemon) => {
const option = document.createElement('option');
option.value = pokemon.url;
option.textContent = pokemon.name;
select.appendChild(option);
});
} catch (error) {
console.error('Error fetch pokemon list:', error);
}
}

async function fetchImage(pokemonUrl) {
try {
const data = await fetchData(pokemonUrl);
const img = document.querySelector('img');
img.src = data.sprites.front_default;
img.alt = `${data.name} Pokemon sprite`;
} catch (error) {
console.error('Error fetch image:', error);
}
}
// Main function to set up event listeners and initialize the app
function main() {
// TODO complete this function
const button = document.createElement('button');
button.id = 'get-button';
button.textContent = 'get pokemon';
document.body.appendChild(button);

const select = document.createElement('select');
select.id = 'pokemon-select';
document.body.appendChild(select);

const option = document.createElement('option');
option.value = '';
option.textContent = 'Select a Pokemon';
select.appendChild(option);

const img = document.createElement('img');
img.id = 'pokemon-img';
img.alt = `select a pokemon to see it image `;
document.body.appendChild(img);

button.addEventListener('click', fetchAndPopulatePokemons);

select.addEventListener('change', (event) => {
if (event.target.value) {
fetchImage(event.target.value);
}
});
}

window.addEventListener('load', main);
41 changes: 41 additions & 0 deletions 3-UsingAPIs/Week2/assignment/ex2-pokemonApp/style.css
Original file line number Diff line number Diff line change
@@ -1 +1,42 @@
/* add your styling here */
/* Basic Reset and Setup */
body {
font-family: Arial, sans-serif;
display: flex; /* Arrange items */
flex-direction: column; /* Stack them vertically */
align-items: center; /* Center them horizontally */
margin-top: 50px; /* Add some space from the top */
background-color: #f4f4f4; /* Light background color */
}

/* Style for the Button and Select */
#get-button, #pokemon-select {
padding: 10px 15px;
margin-bottom: 20px;
border-radius: 5px;
border: 1px solid #ccc;
font-size: 16px;
cursor: pointer;
}

#get-button {
background-color: #3498db; /* A nice blue color */
color: white;
border-color: #2980b9;
transition: background-color 0.2s;
}

#get-button:hover {
background-color: #2980b9;
}

/* Style for the Image */
#pokemon-img {
max-width: 200px; /* Keep the image at a reasonable size */
height: auto;
padding: 15px;
border: 1px solid #ddd;
border-radius: 8px;
background-color: white; /* White background for the sprite */
box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1); /* Subtle shadow */
}
28 changes: 14 additions & 14 deletions 3-UsingAPIs/Week2/assignment/ex3-rollAnAce.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,24 @@ import { rollDie } from '../../helpers/pokerDiceRoller.js';
* @param {DieFace} desiredValue
* @returns {Promise<DieFace>}
*/
export function rollDieUntil(desiredValue) {
// TODO rewrite this function using async/await
return rollDie().then((value) => {
if (value !== desiredValue) {
return rollDieUntil(desiredValue);
}
return value;
});
export async function rollDieUntil(desiredValue) {
let value;
while (value !== desiredValue) {
value = await rollDie();
}
return value;
}

// TODO refactor this function to use try/catch
function main() {
rollDieUntil('ACE')
.then((results) => console.log('Resolved!', results))
.catch((error) => console.log('Rejected!', error.message));
async function main() {
try {
const result = await rollDieUntil('ACE');
console.log('Resolved!', result);
} catch (error) {
console.log('Rejected!', error.message);
}
}

// ! Do not change or remove the code below
if (process.env.NODE_ENV !== 'test') {
main();
}
}
27 changes: 19 additions & 8 deletions 3-UsingAPIs/Week2/assignment/ex4-diceRace.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,31 @@ import { rollDie } from '../../helpers/pokerDiceRoller.js';

export function rollDice() {
const dice = [1, 2, 3, 4, 5];
// TODO complete this function; use Promise.race() and rollDie()
rollDie(1); // TODO placeholder: modify as appropriate
// Each die rolls independently (returns a Promise)
const dicePromises = dice.map(() => rollDie());
// Return a promise that resolves when the first die finishes rolling
return Promise.race(dicePromises);
}

// Refactor this function to use async/await and try/catch
function main() {
rollDice()
.then((results) => console.log('Resolved!', results))
.catch((error) => console.log('Rejected!', error.message));
// Refactored using async/await and try/catch
async function main() {
try {
const winner = await rollDice();
console.log('Resolved!', winner);
} catch (error) {
console.log('Rejected!', error.message);
}
}

// ! Do not change or remove the code below
if (process.env.NODE_ENV !== 'test') {
main();
}

// TODO Replace this comment by your explanation that was asked for in the assignment description.
/*------------------------------------------------------------------------------
Explanation:
Some dice continue rolling after Promise.race() resolves because
Promise.race() only resolves/rejects based on the *first* promise that settles.
The other promises keep running in the background until they complete,
but their results are ignored.
*/
25 changes: 20 additions & 5 deletions 3-UsingAPIs/Week2/assignment/ex5-vscDebug.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,18 @@ async function getData(url) {

function renderLaureate({ knownName, birth, death }) {
console.log(`\nName: ${knownName.en}`);
console.log(`Birth: ${birth.date}, ${birth.place.locationString}`);
console.log(`Death: ${death.date}, ${death.place.locationString}`);

if (birth) {
console.log(`Birth: ${birth?.date || 'Unknown'}, ${birth?.place?.locationString || 'Unknown'}`);
} else {
console.log(`Birth: Unknown`);
}

if (death) {
console.log(`Death: ${death?.date || 'Unknown'}, ${death?.place?.locationString || 'Unknown'}`);
} else {
console.log(`Death: still alive`);
}
}

function renderLaureates(laureates) {
Expand All @@ -20,13 +30,18 @@ function renderLaureates(laureates) {

async function fetchAndRender() {
try {
const laureates = getData(
const data = await getData(
'http://api.nobelprize.org/2.0/laureates?birthCountry=Netherlands&format=json&csvLang=en'
);
renderLaureates(laureates);

if (Array.isArray(data.laureates)) {
renderLaureates(data.laureates);
} else {
console.error('No laureates found.');
}
} catch (err) {
console.error(`Something went wrong: ${err.message}`);
}
}

fetchAndRender();
fetchAndRender();
Loading