Skip to content

London | Nadarajah_Sripathmanathan | book -library | Module-Data-Flows #178

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: book-library
Choose a base branch
from
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
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
node_modules
**/node_modules
.DS_Store
**/.DS_Store
**/.DS_Store../..
12 changes: 6 additions & 6 deletions Sprint-1/destructuring/exercise-1/exercise.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
const personOne = {
name: "Popeye",
age: 34,
favouriteFood: "Spinach",
favoriteFood: "Spinach",
};

// Update the parameter to this function to make it work.
// Don't change anything else.
function introduceYourself(___________________________) {
// Updated function with parameter destructuring
function introduceYourself({ name, age, favoriteFood }) {
console.log(
`Hello, my name is ${name}. I am ${age} years old and my favourite food is ${favouriteFood}.`
`Hello, my name is ${name}. I am ${age} years old and my favorite food is ${favoriteFood}.`
);
}

introduceYourself(personOne);
// Call the function
introduceYourself(personOne);
42 changes: 12 additions & 30 deletions Sprint-1/destructuring/exercise-1/readme.md
Original file line number Diff line number Diff line change
@@ -1,33 +1,15 @@
We can use object destructuring to extract values from an object and assign them to variables in one line.

```js
let person = {
firstName: "Bruce",
lastName: "Wayne",
const personOne = {
name: "Popeye",
age: 34,
favoriteFood: "Spinach",
};

let { firstName, lastName } = person;

console.log(`Batman is ${firstName}, ${lastName}`);
```

The program above will print `Batman is Bruce Wayne`.

This is more concise than doing this without object destructuring:

```js
let person = {
firstName: "Bruce",
lastName: "Wayne",
};

let firstName = person.firstName;
let lastName = person.lastName;

console.log(`Batman is ${firstName}, ${lastName}`);
```

# Exercise
// Updated function with parameter destructuring
function introduceYourself({ name, age, favoriteFood }) {
console.log(
`Hello, my name is ${name}. I am ${age} years old and my favorite food is ${}.`
);
}

- What is the syntax to destructure the object `personOne` in exercise.js?
- Update the parameter of the function `introduceYourself` to use destructuring on the object that gets passed in.
// Call the function
introduceYourself(personOne);
18 changes: 17 additions & 1 deletion Sprint-1/destructuring/exercise-2/exercise.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ let hogwarts = [
{
firstName: "Cedric",
lastName: "Diggory",
house: "HufflePuff",
house: "Hufflepuff",
pet: null,
occupation: "Student",
},
Expand Down Expand Up @@ -70,3 +70,19 @@ let hogwarts = [
occupation: "Teacher",
},
];

// Task 1: Gryffindor members
console.log("Gryffindor members:");
for (const { firstName, lastName, house } of hogwarts) {
if (house === "Gryffindor") {
console.log(`${firstName} ${lastName}`);
}
}

// Task 2: Teachers with pets
console.log("\nTeachers with pets:");
for (const { firstName, lastName, occupation, pet } of hogwarts) {
if (occupation === "Teacher" && pet) {
console.log(`${firstName} ${lastName}`);
}
}
45 changes: 35 additions & 10 deletions challenges/challenge-cowsay-two/solution1.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,51 @@
// =================

// 1. Accept arguments

// how will you accept arguments?
const args = process.argv.slice(2); // Get arguments after node and script name
const saying = args.join(' '); // Join arguments into a single string

// 2. Make supplies for our speech bubble

let topLine = '_';
let bottomLine = '-';
let saying = '';

// 3. Make a cow that takes a string

function cowsay(saying) {
// how will you make the speech bubble contain the text?

// where will the cow picture go?

// how will you account for the parameter being empty?

if (!saying) {
saying = "Moo!"; // Default saying if none provided
}

const maxLength = saying.length;
const topBorder = ' ' + topLine.repeat(maxLength + 2);
const bottomBorder = ' ' + bottomLine.repeat(maxLength + 2);

let speechBubble = '';

if (maxLength === 0) {
speechBubble = `
${topBorder}
< >
${bottomBorder}
`;
} else {

speechBubble = `
${topBorder}
< ${saying} >
${bottomBorder}
`;
}
const cow = `
\\ ^__^
\\ (oo)\\_______
(__)\\ )\\/\\
||----w |
|| ||
`;
return speechBubble + cow;
}

//4. Pipe argument into cowsay function and return a cow

// how will you log this to the console?
console.log(cowsay(saying));
41 changes: 33 additions & 8 deletions challenges/challenge-cowsay-two/solution2.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,36 @@

// 2. Make supplies for our speech bubble

// 3. Make a cow that takes a string

const cow = (saying) => {
// how did you make the cow before?
}

// 4. Use readline to get a string from the terminal
// (with a prompt so it's clearer what we want)
const createSpeechBubble = (saying) => {
const lines = saying.split('\n');
const maxLength = Math.max(...lines.map(line => line.length));
const top = ' ' + '_'.repeat(maxLength + 2) + ' ';
const bottom = ' ' + '-'.repeat(maxLength + 2) + ' ';
const middle = lines.map(line => {
const padding = ' '.repeat(maxLength - line.length);
return `| ${line}${padding} |`;
}).join('\n');
return `${top}\n${middle}\n${bottom}`;
};

// 3. Make a cow that takes a string

const cow = (saying) => {
const speechBubble = createSpeechBubble(saying);
return `${speechBubble}\n \\ ^__^\n \\ (oo)\\_______\n (__)\\ )\\/\\\n ||----w |\n || ||`;
};

// 4. Use readline to get a string from the terminal
// (with a prompt so it's clearer what we want)

const readline = require('readline');

const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});

rl.question('What does the cow say? ', (saying) => {
console.log(cow(saying));
rl.close();
});
1 change: 1 addition & 0 deletions challenges/challenge-weather-app/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ <h1 class="title">
</main>

<!-- JS goes here -->
<script src="weather.js"></script>
</body>

</html>
109 changes: 109 additions & 0 deletions challenges/challenge-weather-app/weather.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
// weather.js

const weatherApiKey = 'a905f933c527562a1ab40ad9c7c87c8e'; // Replace with your OpenWeather API key
const unsplashApiKey = 'YOUR_UNSPLASH_API_KEY'; // Replace with your Unsplash API key

const cityInput = document.getElementById('cityInput');
const searchButton = document.getElementById('searchButton');
const photosDiv = document.getElementById('photos');
const thumbsDiv = document.getElementById('thumbs');

async function getWeatherData(city) {
const weatherUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&APPID=${weatherApiKey}&units=metric`;
try {
const response = await fetch(weatherUrl);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching weather data:', error);
return null;
}
}

async function getUnsplashImages(query) {
const unsplashUrl = `https://api.unsplash.com/search/photos?query=${query}&client_id=${unsplashApiKey}`;
try {
const response = await fetch(unsplashUrl);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.results;
} catch (error) {
console.error('Error fetching Unsplash images:', error);
return null;
}
}

function displayMainImage(imageUrl, photographerName, photographerLink) {
photosDiv.innerHTML = '';
const img = document.createElement('img');
img.src = imageUrl;
img.alt = 'Main Image';
photosDiv.appendChild(img);

const creditDiv = document.createElement('div');
creditDiv.classList.add('credit');
creditDiv.innerHTML = `Photo by <a href="${photographerLink}" target="_blank">${photographerName}</a> on Unsplash`;
photosDiv.appendChild(creditDiv);
}

function displayThumbnails(images) {
thumbsDiv.innerHTML = '';
images.forEach(image => {
const thumb = document.createElement('img');
thumb.src = image.urls.thumb;
thumb.alt = image.alt_description;
thumb.classList.add('thumbnail');

thumb.addEventListener('click', () => {
displayMainImage(image.urls.regular, image.user.name, image.user.links.html);
setActiveThumbnail(thumb);
});

thumbsDiv.appendChild(thumb);
});
if(images.length > 0){
displayMainImage(images[0].urls.regular, images[0].user.name, images[0].user.links.html);
setActiveThumbnail(thumbsDiv.firstChild);
}

}

function setActiveThumbnail(thumbnail) {
document.querySelectorAll('.thumbnail').forEach(t => t.classList.remove('active'));
thumbnail.classList.add('active');
}

async function updateWeatherAndImages(city) {
const weatherData = await getWeatherData(city);
if (weatherData) {
const weatherDescription = weatherData.weather[0].description;
const images = await getUnsplashImages(weatherDescription);
if (images) {
displayThumbnails(images);
}
}
}

searchButton.addEventListener('click', () => {
const city = cityInput.value;
if (city) {
updateWeatherAndImages(city);
}
});

cityInput.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
const city = cityInput.value;
if (city) {
updateWeatherAndImages(city);
}
}
});

// Initial load (default city: London)
updateWeatherAndImages('London');
52 changes: 52 additions & 0 deletions challenges/dog-photo-gallery/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Dog Gallery</title>
</head>
<body>
<button id="fetchButton">Fetch Dog Image</button>
<button id="clearButton">Clear Images</button>
<ul id="dogList"></ul>

<script>
const fetchButton = document.getElementById('fetchButton');
const clearButton = document.getElementById('clearButton');
const dogList = document.getElementById('dogList');

fetchButton.addEventListener('click', fetchDogImage);
clearButton.addEventListener('click', clearImages);

function fetchDogImage() {
fetch('https://dog.ceo/api/breeds/image/random')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
const imageUrl = data.message;
const listItem = document.createElement('li');
const img = document.createElement('img');
img.src = imageUrl;
img.style.maxWidth = '300px'; // Limit image size
listItem.appendChild(img);
dogList.appendChild(listItem);
})
.catch(error => {
console.error('Error fetching dog image:', error);
const listItem = document.createElement('li');
listItem.textContent = 'Failed to load image. Please try again.';
dogList.appendChild(listItem);
});
}

function clearImages(){
dogList.innerHTML = '';
}

</script>
</body>
</html>
Loading