diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..6f3a2913 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "liveServer.settings.port": 5501 +} \ No newline at end of file diff --git a/homework-projects/assets/API-guide-1.png b/homework-projects/assets/API-guide-1.png new file mode 100644 index 00000000..958df4fc Binary files /dev/null and b/homework-projects/assets/API-guide-1.png differ diff --git a/homework-projects/assets/API-guide-2.png b/homework-projects/assets/API-guide-2.png new file mode 100644 index 00000000..ceadfbe7 Binary files /dev/null and b/homework-projects/assets/API-guide-2.png differ diff --git a/homework-projects/assets/API-guide-3.png b/homework-projects/assets/API-guide-3.png new file mode 100644 index 00000000..08937a17 Binary files /dev/null and b/homework-projects/assets/API-guide-3.png differ diff --git a/homework-projects/assets/API-guide-4.png b/homework-projects/assets/API-guide-4.png new file mode 100644 index 00000000..6176f249 Binary files /dev/null and b/homework-projects/assets/API-guide-4.png differ diff --git a/homework-projects/assets/memory-game-card-flip.gif b/homework-projects/assets/memory-game-card-flip.gif new file mode 100644 index 00000000..df22983d Binary files /dev/null and b/homework-projects/assets/memory-game-card-flip.gif differ diff --git a/homework-projects/assets/memory-game-grid.png b/homework-projects/assets/memory-game-grid.png new file mode 100644 index 00000000..236b0f3f Binary files /dev/null and b/homework-projects/assets/memory-game-grid.png differ diff --git a/homework-projects/assets/memory-game-pattern.png b/homework-projects/assets/memory-game-pattern.png new file mode 100644 index 00000000..de65a79c Binary files /dev/null and b/homework-projects/assets/memory-game-pattern.png differ diff --git a/homework-projects/assets/movie-app-star-rating.gif b/homework-projects/assets/movie-app-star-rating.gif new file mode 100644 index 00000000..09602c4a Binary files /dev/null and b/homework-projects/assets/movie-app-star-rating.gif differ diff --git a/homework-projects/assets/project-flow.png b/homework-projects/assets/project-flow.png new file mode 100644 index 00000000..9739dff2 Binary files /dev/null and b/homework-projects/assets/project-flow.png differ diff --git a/homework-projects/guides/demo-day-presentation.md b/homework-projects/guides/demo-day-presentation.md new file mode 100644 index 00000000..cfce99db --- /dev/null +++ b/homework-projects/guides/demo-day-presentation.md @@ -0,0 +1,29 @@ +# Demo Day Presentation + +Your team may choose to run a demo day to present your project and get feedback. If so, here's a brief to guide you through your 15-minute presentation. Each individual will have 40-minutes in total, broken down into 15-minutes for presenting and 25-minutes for discussions. Your presentation will be an opportunity to showcase your project, detail your weekly progress, and share your challenges and learnings. + + +## Presentation Structure (15 minutes) + +### Introduction (2 minutes) +Briefly introduce your chosen project. (Refer to the "projects" folder for details.) + +### Weekly Task Breakdown (10 minutes) +For each week of the JS2 and JS3 modules, highlight: +- Your understanding and implementation of their concepts. +- Specific challenges you faced and how you overcame them. +- Any particular successes or insights you gained. + +### Project Summary (3 minutes) +Summarize what you learned from this project and how it ties together the concepts learned over JS2 and JS3. + +### Feedback and Discussion Session (25 minutes) + +After your presentation, there will be an open session for feedback and discussion. This is a valuable time to gain insights from your mentors and peers. + +Tips for a Successful Presentation: +- Be Clear and Concise: Focus on the key points and challenges of your project while being mindful of time. +- Reflect on Your Learning Journey: Share how your understanding evolved over the weeks. +- Be Open to Feedback: This is a learning opportunity – embrace the insights and suggestions from mentors and peers. + +This is a suggested guideline for you to follow. We look forward to seeing your projects and hearing about your journey through the JS2 and JS3 modules in a way that works for you and your project. Good luck! diff --git a/homework-projects/guides/making-your-API-guide.md b/homework-projects/guides/making-your-API-guide.md new file mode 100644 index 00000000..5166ef68 --- /dev/null +++ b/homework-projects/guides/making-your-API-guide.md @@ -0,0 +1,68 @@ +# Build your own API + +[GitHub Pages](https://pages.github.com/) is a good place to host a site for your portfolio or a project, but another excellent use for it is to host your own JSON API data! + +All you would need to do, in short, is create a GitHub Pages repository, put a JSON file in there, and your custom URL will have all of that data from the JSON file. See below for more detailed instructions and some screenshots to help you get around! + +## Instructions + +### Creating the repository + +The first thing you’ll need to do is create a GitHub Pages repository. + +Head on over to your GitHub account and create a repository called *`username`*.github.io, where *`username`* is your GitHub username. + +If you already have such a repository, just go on to the next step. + +![Create the repo](/homework-projects/assets/API-guide-1.png) + +❗Make sure that it matches your username or it won’t work! + +❗It seems like the repository can be private if you will just use it for the API, but has to be public if you also want to use it to [create a site](https://pages.github.com/). ([see here](https://docs.github.com/en/pages/getting-started-with-github-pages/creating-a-github-pages-site#:~:text=GitHub%20Pages%20is%20available%20in%20public%20repositories%20with%20GitHub%20Free%20and%20GitHub%20Free%20for%20organizations%2C%20and%20in%20public%20and%20private%20repositories%20with%20GitHub%20Pro%2C%20GitHub%20Team%2C%20GitHub%20Enterprise%20Cloud%2C%20and%20GitHub%20Enterprise%20Server.%20For%20more%20information%2C%20see%20%22GitHub%E2%80%99s%20plans.%22) for more information) + +### Adding the JSON file + +1. Once the repository has been made, head over to your terminal and clone that repository into a directory of your choosing. +2. Once the repository been cloned to your computer, open the project folder in VS Code. +3. Create a folder for your APIs or just create a file in the root of the repository. You might want to organize it into a folder (fx. “data”) if you plan to create more APIs in the future and/or if you plan to also host your site on Github Pages. In the case of your JS project, you would just copy and paste the array of objects that you have been using so far and perhaps add more objects to it, if needed. +4. Once you are ready with your JSON file, add, commit and push the changes to `main` so that you have the file on your repository. +5. Head over to the repo on GitHub and verify that your file is there and that all is good. + +![See the JSON file](/homework-projects/assets/API-guide-2.png) + +❗Be mindful about your data format. Note wether you should use an object or an array of objects and form your file accordingly. + +### Using the API + +Now comes the fun part! You can use the JSON file in a FETCH to get and use the data dynamically. + +Your URL for FETCH will be the raw content of the JSON file that you added. Head on to the `raw` version of your file: + +![Access the raw content](/homework-projects/assets/API-guide-3.png) + +Copy the URL and use it for fetching the data. + +![Copy the URl](/homework-projects/assets/API-guide-4.png) + +Now you have a publicly hosted API! To access this information, all you need to do is make an API call like you normally would (FETCH), parse that data (iterate through an array of objects), and then use the data in whatever way you need for your project! + +❗Note that in Vanilla JS (which is what you are learning now), you cannot access the fetched data outside of your fetch function. So you will most probably need to move your whole code from before into the function or call the necessary functions from within the FETCH function, something like this: + +```jsx +async function getData() { + const response = await fetch( + "https://raw.githubusercontent.com/shpomp/shpomp.github.io/main/test.json?token=<>" + ); + const myData = await response.json(); + + theFunctionThatUsesYourData(myData); +} + +const theFunctionThatUsesYourData = (data) => { + for (const item of data) { + // your code .... + } +}; + +// other code ... +``` diff --git a/homework-projects/guides/weekly-submission-guide.md b/homework-projects/guides/weekly-submission-guide.md new file mode 100644 index 00000000..db1c2d17 --- /dev/null +++ b/homework-projects/guides/weekly-submission-guide.md @@ -0,0 +1,94 @@ +# HOMEWORK SUBMISSION + +## TL;DR + +- [ ] start any coding session from `main`. +- [ ] periodically keep your local `main` up to date with changes in the remote `main` (for example, when you merge a PR on GitHub, your remote `main` gets the new code added, but your local `main` does not). +- [ ] periodically merge the up-to-date local `main` into your new homework branch. +- [ ] always checkout to a new homework branch from `main`. +- [ ] write meaningful commit messages. +- [ ] before pushing, double check that your branch name is correct. +- [ ] if the branch name is not correct, you can checkout to a new, correct branch from the current branch - you will carry all the commits with you. +- [ ] stay patient. Slack, Google and ChatGPT are your best friends now. +- [ ] make the changes as per PR review in the appropriate branch, push the changes to the appropriate branch and merge the PR. + +
+ +
+
+ +## Before you start the project + +- Create a public project repository in your GitHub account (choose the option to add README.md). +- Clone the repository locally and open it in VS code. + +## Before you start your homework + +1. You are probably opening your project repo on the last weeks branch - make sure that any changes you have there are either committed and pushed, or stashed, or discarded - whatever you prefer. The point is to be mindful that: +
- you are most probably starting on a branch you last worked with, that is how VS Code works, +
- and there might be changes that you have not handled last time. +
- if you are about to start a new homework, you need to go to `main` first. + +
+ +2. Checkout to `main` and pull the latest changes from it. If you skip this step, you will get in trouble sooner or later. + +
+ +3. Checkout to your new homework branch, following the branch naming convention of `module-week/yourname`. + See [allowed branch name prefixes](#allowed-branch-name-prefixes). + +
+❗ Always firstly checkout to the new homework branch from an updated `main`. Always. + +
+ +### Allowed branch name prefixes: + +| | | | | | +| ----------------- | ----------------- | ----------------- | --- | --- | +| javascript2-week1 | javascript2-week2 | javascript2-week3 | | +| javascript3-week1 | javascript3-week2 | javascript3-week3 | | + +### Examples + +> ❌ javascript3/maria
+> ❌ javascript2-week1-homework
+> ❌ javascript3-week2
+> ✅ javascript3-week3/maria + +
+ +## Completing and submitting your homework + +1. Implement your homework. Be mindful of structuring and naming. Make sure you complete all the tasks listed for that week in your project description. + +
+ +2. Verify that your branch name is right. Commit and push your homework to the repository. If the branch name is not right, you can commit and checkout to a new, correct branch from the current branch - you will carry all the commits with you. Then you can push. + +
+ +3. Go to your project repository and create a Pull Request from your weekly homework branch to `main`. + +
+ +4. Post the link to the PR to your class channel and celebrate with your classmates! 🎉 💃🏽 🕺🏾 🥳 + +
+ +## After submitting your homework + +1. Follow the PR to see the review and interact with the reviewer as well as make the suggested changes. + +
+ +2. When you have made changes to the code since the homework submission and review, push the changes and merge the PR. + +
+ +3. Update your local `main` with the merged changes in the remote `main`. + +
+ +4. Take a moment to celebrate your progress and be proud of your learning! diff --git a/homework-projects/projects/currency-converter/currency-converter.md b/homework-projects/projects/currency-converter/currency-converter.md new file mode 100644 index 00000000..ba685c41 --- /dev/null +++ b/homework-projects/projects/currency-converter/currency-converter.md @@ -0,0 +1,117 @@ +![](https://media.giphy.com/media/LdOyjZ7io5Msw/giphy.gif) + +# CURRENCY CONVERTER + +You started working in a new cool fintech startup, and your first task is to build a simple currency converter app. +It is expected that your app will have at least these features and functionality: + +- Insert a new currency rate +- List currencies and rates +- Search currencies +- Set a rate to be alerted when a currency reaches that rate +- The ‘most moving’ currency rate +- Timeout for the market open/close +- Call the currency API to receive the rates dynamically + +> [!NOTE] +> Take some time to research online for similar apps and how they look and work to gain inspiration. This is an important skill to practice as a developer because you won't always know (or be told) how to approach the design. + +## Weekly specs: + +### `JS2 week1` - Browser environment, DOM manipulation, DOM event listeners + +- [ ] Create a form to insert a brand new currency rate from `a` to `b`. +- [ ] Create a form to covert an amount of money from `x` currency to `y` based on the rates provided. +- [ ] optional bonus: create a form to update existing currency conversion with a new rate. +
+ +Your currency rate object format could be something like this: + +```js +{ + "timestamp": 1519296206, + "base": "EUR", + "date": "2021-03-17", + "rates": { + "USD": 1.23396, + [...] + } +} +``` + +The above would be how a brand new currency rate could look like (the first task). +Then, after an update (the bonus task) it could look something like this: + +```js +{ + "timestamp": 1519296206, + "base": "EUR", + "date": "2021-03-17", + "rates": { + "USD": 1.23396, + "GBP": 0.882047, + [...] + } +} +``` + +--- + +### `JS2 week2` - Array functions, Arrow function + +Start with creating an array of currency rate objects. Even a small one is perfectly enough, but go as big as you want! +Continue with the format of the object you used last week or improve it and refactor! + +- [ ] List: Traverse through your array of the currency rate objects, and display them in a grid of items containing all the relevant details. +- [ ] Implement a function to find a specific currency rate, searching by the currency `from` or `to`.
+ Basically, it is just a search function! With a twist, though, because you have both the `from` and the `to` fields. + As a user, I want to find a specific rate, but I am too lazy to scan through all the rates with my eyes, I want to be able to type in and search! + +--- + +### `JS2 week3` - Callback function, Asynchronicity, Scope + +- [ ] Implement a timeout to show an announcement when the market open or/and close. The market opens at 9AM and closes at 5PM local time. + +- [ ] optional bonus: + a. Implement a watcher to periodically check a specific currency conversion and alert the user when the value reaches a speicfic point. Let's say the user is interested in converting USD to Danish kroner but the rate today is very bad, 1 USD is 5 DKK. We wan to alert the user when 1 USD is 7 DKK so the user can convert with maximum gain + b. Watch currency updates and show a banner with the hotest currency exchange rate. I.e., currency conversion reaching the double value. + +--- + +### `JS3 week1` - Json, Apis, Fetch + +- [ ] Follow the [API creation guide](/homework-projects/guides/making-your-API-guide.md) to make your own API that you will use from now on. +- [ ] Refactor your code so that you use the currency rates dynamically from your API instead of the static array of objects. +- [ ] Implement functionality to search for a specific currency. +- [ ] Ensure all the functionality is working smoothly after refactoring. + +--- + +### `JS3 week2` - Promises, Async/Await + +- [ ] You used promise chaining last week - now rewrite the fetch in the "async await" approach. +- [ ] Testing. Implement a test to ensure that the application will work as expected after the refactoring. + +--- + +### `JS3 week3` - Classes, Revision and Presentation of projects + +- [ ] Rest, revise JS fundamentals, finish, and brush up your project, prepare to present and explain it. +- [ ] Make improvements to the style or functionality or add additional functionality. +- [ ] Prepare to showcase your project to external people, talk through your code and explain what you have implemented. + +--- + +
+
+ +## Project completion checklist ✅ + +- [ ] I can insert a new currency rate +- [ ] I can see a list of all currencies and rates +- [ ] I can use the coverter to convert a currency and see the result +- [ ] I can search currencies to find a specific one +- [ ] I can set a rate to be alerted when a currency reaches that rate +- [ ] I can see an indicator for the market open/close +- [ ] I am using the currency API to receive the rates dynamically diff --git a/homework-projects/projects/memory-game/card-backside.jpg b/homework-projects/projects/memory-game/card-backside.jpg new file mode 100644 index 00000000..3c61a6c6 Binary files /dev/null and b/homework-projects/projects/memory-game/card-backside.jpg differ diff --git a/homework-projects/projects/memory-game/card-picture.jpg b/homework-projects/projects/memory-game/card-picture.jpg new file mode 100644 index 00000000..a5fe247d Binary files /dev/null and b/homework-projects/projects/memory-game/card-picture.jpg differ diff --git a/homework-projects/projects/memory-game/memory-game.md b/homework-projects/projects/memory-game/memory-game.md new file mode 100644 index 00000000..f8c61cc9 --- /dev/null +++ b/homework-projects/projects/memory-game/memory-game.md @@ -0,0 +1,89 @@ +![](https://media.giphy.com/media/374pcIBVEGb6g/giphy.gif) + +# MEMORY GAME + +You joined an online game platform startup and your task is to build one of the small classic games.
+You will build a Memory Game, where a user needs to flip all the cards in a game in pairs until they find all the matching pairs. You aspire to make the game smooth and pleasant, so the user is compelled to spend more time playing it. + +> [!NOTE] +> Take some time to research online for similar apps and how they look and work to gain inspiration. This is an important skill to practice as a developer because you won't always know (or be told) how to approach the design. + +## Weekly specs: + +### `JS2 week1` - Browser environment, DOM manipulation, DOM event listeners + +You are provided with a picture and a card backside pattern picture (or pick your own). + +- [ ] display a single card on the page using DOM manipulation. +- [ ] implement the functionality of flipping the card: on click, the card flips from showing the backside pattern to the picture and vice versa. Visual animation is optional and the exact look of it is up to you! + + + +--- + +### `JS2 week2` - Array functions, Arrow function + +Start with creating an array of picture objects. Even a small one is perfectly enough, but go as big as you want! A picture object should ideally have at least an id, a name and a picture url. +Continue with the format of the picture object you used last week or improve it and refactor! + +- [ ] generate a new array where each card object is added to it twice, but in a random order. Think about _doubling_ and _shuffling_ an array when you research how to complete this task. +- [ ] traverse through the new array of picture objects and display all the cards in a grid. +- [ ] include the functionality from the previous week so that each card will flip from the picture to the backside pattern and back when it is clicked. + +![](/assets/memory-game-grid.png) + +--- + +### `JS2 week3` - Callback function, Asynchronicity, Scope + +- [ ] implement a counter for how many times in total you have flipped a card (one counter for all the cards). Note that you are not supposed to count clicks! The purpose is to count how many times you have _revealed_ the card picture - in other words, you are couunting player moves. +- [ ] implement a timer for how much time has passed since you first clicked on a card. +- [ ] adjust the functionality so that once 2 cards are flipped, they stay flipped for X seconds, after which they flip back down automatically. + +--- + +### `JS3 week1` - Json, Apis, Fetch + +- [ ] follow the [API creation guide](/homework-projects/guides/making-your-API-guide.md) to make your own API that you will use from now on. +- [ ] refactor your code so that you ditch the static array of objects and instead fetch the cards data from your API. +- [ ] ensure all the functionality is working smoothly after refactoring. + +--- + +### `JS3 week2` - Promises, Async/Await + +- [ ] you used promise chaining last week - now rewrite the fetch in the "async await" approach. +- [ ] implement the functionality for it to work like and actual memory game: + +At least: + +- You can only flip 2 cards at a time. +- If the cards match, they are removed from the DOM. +- The game reloads once all cards are removed. + +At most: + +- Implement the tasks listed under "At least". +- Use the counter and timer that you implemented before and stop the game when a certain count or time is reached. The time or count can be hardcoded or user-submitted via an input. + +--- + +### `JS3 week3` - Classes, Revision and Presentation of projects + +- [ ] rest, revise JS fundamentals, finish, and brush up your project, prepare to present and explain it. +- [ ] make improvements to the style or functionality or add additional functionality. +- [ ] Prepare to showcase your project to external people, talk through your code and explain what you have implemented. + +
+
+ +## Project completion checklist ✅ + +- [ ] at first, I can see a square grid of cards "flipped down" - seeing their backside pattern; +- [ ] I can click on a card, which makes the card "flip" and reveal the picture/gif; +- [ ] I can only reaveal 2 cards at a time; +- [ ] the 2 revealed cards stay flipped for X seconds, after which they flip down again; +- [ ] if I reveal 2 matching cards, they are removed from the page; +- [ ] I can see a timer that starts once I flip the very first card in a new game; +- [ ] I can see a counter that counts how many times I have flipped a card; +- [ ] once all cards are removed, the game reloads. diff --git a/homework-projects/projects/movie-app/movie-app.md b/homework-projects/projects/movie-app/movie-app.md new file mode 100644 index 00000000..312ec452 --- /dev/null +++ b/homework-projects/projects/movie-app/movie-app.md @@ -0,0 +1,106 @@ +![](https://media.giphy.com/media/KZe02gpoAj4yVjxKQt/giphy.gif) + +# MOVIE APP + +You joined a startup that has the ambition to build the best new movie streaming platform!
+Your taks will be to build a simple prototype to showcase the look of the platform and some simple functionality.
+Your way to impress is to not only build a nice-looking main movie list page, but to also include some interesting features that the competitors do not have! + +> [!NOTE] +> Take some time to research online for similar apps and how they look and work to gain inspiration. This is an important skill to practice as a developer because you won't always know (or be told) how to approach the design. + +## Weekly specs: + +### `JS2 week1` - Browser environment, DOM manipulation, DOM event listeners + +Use a movie object with details such as id, title, description, year, main actors, etc. + +It could be something like this: + +```js + { + id: 1, + title: 'Interstellar', + description: + 'The adventures of a group of explorers who make use of a newly discovered wormhole to surpass the limitations on human space travel and conquer the vast distances involved in an interstellar voyage.', + movie_year: 2014, + director: "Christopher Nolan", + actors: ["Matthew McConaughey", "Anne Hathaway", "Jessica Chastain", "Michael Caine", "Casey Affleck", "Mackenzie Foy", "John Lithgow", "Ellen Burstyn", "Matt Damon"], + poster_url: + 'https://www.themoviedb.org/t/p/w600_and_h900_bestv2/gEU2QniE6E77NI6lCU6MxlNBvIx.jpg', + price: '120.00', + }, +``` + +Add whatever properties you think are relevant and that you want to display as the information on your future movie website! + +- [ ] design and implement the layout of the movie card via DOM manipulation. + +- [ ] via DOM manipulation, implement one of the two (or both!):
+ a. submitting and displaying a comment about the movie. Implement an imput under the movie and a functionality to display the submitted comment.
+ b. rating the movie in a star-rating format and displaying the submitted rating. +
+ + + +--- + +### `JS2 week2` - Array functions, Arrow function + +Start with creating an array of movie objects. Even a small one is perfectly enough, but go as big as you want! +Continue with the format of the movie object you used last week or improve it and refactor! + +- [ ] traverse the movie array and display all the movies on the page in a grid via DOM manipulation. +- [ ] manipulate the movie array, implementing these functions: +- a function for searching for a provided keyword in the movie title; +- a function for sorting the movie array by one or a few selected properties. +- [ ] optional: as you might guess, you will later use these functions to implement searching and sorting functionality, so feel free to add any other array-manipulation functions of your choice! + +--- + +### `JS2 week3` - Callback function, Asynchronicity, Scope + +Here you will develop some features that will differentiate your movie platform from the competition! + +- [ ] implement a timer where you can set a time for how much time you give yourself to pick a movie to watch, the timer alerts or rings when then time is over. +- [ ] implement a timer to show how long you have spent on the page. + +--- + +### `JS3 week1` - Json, Apis, Fetch + +- [ ] follow the [API creation guide](/homework-projects/guides/making-your-API-guide.md) to make your own API that you will use from now on. +- [ ] refactor your code so that you ditch the static array of objects and instead fetch the movies data from your API. +- [ ] ensure all the functionality is working smoothly after refactoring. + +--- + +### `JS3 week2` - Promises, Async/Await + +- [ ] you used promise chaining last week - now rewrite the fetch in the "async await" approach +- [ ] fit and apply one (or all) of your functions from JS2 week2 to manipulate the displayed movies: + +- a function to search a movie by title that a user submits via an input, displaying only the matching movies. +- a function to sort the movies by a property selected via a dropdown. +- a function to filter the movies by a specific constraint submitted by the user via an input (or hardcoded), only displaying the relevant movies. + +--- + +### `JS3 week3` - Classes, Promises advanced + +- [ ] rest, revise JS fundamentals, finish, and brush up your project, prepare to present and explain it. +- [ ] make improvements to the style or functionality or add additional functionality. + +--- + +
+
+ +## Project completion checklist ✅ + +- [ ] I can see a page with a list of movies displayed in a grid; +- [ ] I can see the most important details about a movie displayed in a nice and readable way; +- [ ] I can either submit a comment to a movie or a star rating or both; +- [ ] I can search for movies by titling, typing in a search keyword; +- [ ] I can sort the movies by at least one specific property; +- [ ] I can filter the movies by at least one user-submitted or hardcoded constraint (f.x. movies older than year X). diff --git a/homework-projects/projects/quiz-app/quiz-app.md b/homework-projects/projects/quiz-app/quiz-app.md new file mode 100644 index 00000000..89f7e705 --- /dev/null +++ b/homework-projects/projects/quiz-app/quiz-app.md @@ -0,0 +1,109 @@ +![](https://media.giphy.com/media/y1JYvLe9fFfpK/giphy.gif) + +# QUIZ APP + +The most popular quiz app has become very expensive... so there came a startup that aspires to build a new one that will be better, cheaper to use and more fun! +You join the startup as a developer and your task is to build a nice prototype of the product while the rest of the product team works to define what the final version will be. + +> [!NOTE] +> Take some time to research online for similar apps and how they look and work to gain inspiration. This is an important skill to practice as a developer because you won't always know (or be told) how to approach the design. + +## Weekly specs: + +### `JS2 week1` - Browser environment, DOM manipulation, DOM event listeners + +- [ ] create a form to insert a quiz question. It should take a question and 4 options for answers. There should be a way to mark which answer is correct in the form, but you should only be able to select one correct answer. + +- [ ] implement one of the two (or both!): + +a. add a button that randomizes the order of the 4 option inputs once they have been filled in. + +b. color the input for the "correct" answer option in green and the "wrong" ones in red. Make sure it's still readable. + +- [ ] optional bonus: make sure the question is not longer than 140 characters. + +The format of the object of the quiz question, for example, could be something like this: + +```js +const quizQuestion = { + id: 1, + question: "What is the capital of Denmark?", + options: [ + { text: "Berlin", isCorrect: false }, + { text: "Copenhagen", isCorrect: true }, + { text: "Madrid", isCorrect: false }, + { text: "Rome", isCorrect: false }, + ], + explanation: "Copenhagen is the capital of Denmark.", +}; +``` + +--- + +### `JS2 week2` - Array functions, Arrow function + +Start with creating an array of quiz question objects. Even a small one is perfectly enough, but go as big as you want! +Continue with the format of the question object you used last week or improve it and refactor! + +- [ ] save the quiz question into an array when the form is submitted. + +- [ ] show a list of all quiz questions added to the array below the form. It should show the questions, the 4 options but not which one is correct. Add a button with the functionality to reveal which is the correct answer for each question. + +- [ ] build a function to filter the questions by searching the content of the question. + +--- + +### `JS2 week3` - Callback function, Asynchronicity, Scope + +- [ ] add inputs for 2 player names and a button to start a quiz. When the quiz starts, player names are displayed with their collected points (0 to begin with). + +- [ ] implement one of the two (or both!): + +a. next to each player's name, add two buttons [correct] and [wrong]. When the "correct" button for a player is pressed, they score 1 point, when the wrong button is pressed, the _other_ player scores one point. + +b. add number inputs for the player points and use the browser's arrow buttons on the input fields to increase/decrease the points. + +- [ ] optional bonus: play a sound and end the quiz game when one of the players has reached 10 points. + +--- + +### `JS3 week1` - Json, Apis, Fetch + +- [ ] follow the [API creation guide](/homework-projects/guides/making-your-API-guide.md) to make your own API that you will use from now on. + +- [ ] refactor your code so that you ditch the static array of objects and instead fetch the initial questions data from your API. + +- [ ] ensure all the functionality is working smoothly after refactoring. + +- [ ] add alphabetical sorting of the questions and random sorting of the questions and let the user choose. + +--- + +### `JS3 week2` - Promises, Async/Await + +- [ ] you used promise chaining last week - now rewrite the fetch in the "async await" approach. + +- [ ] add a search input to filter the questions by searching the content of the question - use the function that you have build before. When you click the search button, display only the questions where the search input is included in the question text. + +--- + +### `JS3 week3` - Classes, Revision and Presentation of projects + +- [ ] rest, revise JS fundamentals, finish, and brush up your project, prepare to present and explain it. +- [ ] make improvements to the style or functionality or add additional functionality. +- [ ] Prepare to showcase your project to external people, talk through your code and explain what you have implemented. + +--- + +
+
+ +## Project completion checklist ✅ + +- [ ] I can see a form to submit a question at the top of the page and a list of questions bellow it; +- [ ] when submitting a new question, I can see an indication where to submit the correct answer; +- [ ] the questions are displayed in a nice and readable way, and I can see a button to reveal the right answer for each question; +- [ ] I can sort the questions alphabetically; +- [ ] I can use search and get the questions wher my search keyword is included in the question text; +- [ ] there is a functionality to submit two player names; +- [ ] it is possible to interact with player scores. diff --git a/homework-projects/projects/recipe-app/recipe-app.md b/homework-projects/projects/recipe-app/recipe-app.md new file mode 100644 index 00000000..c77887ab --- /dev/null +++ b/homework-projects/projects/recipe-app/recipe-app.md @@ -0,0 +1,101 @@ +![](https://media.giphy.com/media/N23cG6apipMmQ/giphy.gif) + +# RECIPE APP + +You are a foood lover, a cooking enthusiast and you want to share your passion with the web. You aspire to build a cool recipe website as a hobby project and eventually earn a little bit on the side from it. + +> [!NOTE] +> Take some time to research online for similar apps and how they look and work to gain inspiration. This is an important skill to practice as a developer because you won't always know (or be told) how to approach the design. + +## Weekly specs: + +### `JS2 week1` - Browser environment, DOM manipulation, DOM event listeners + +Create a recipe object that has at least the id, name, description, a list of ingredients and a picture url. +Or just use the below! + +```js +const recipeObject = { + id: 1, + title: "Gløgg", + picture_url: + "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e2/Gl%C3%B6gg_kastrull.JPG/800px-Gl%C3%B6gg_kastrull.JPG", + ingredients: [ + { NAME: "Orange zest", AMOUNT: "0.5" }, + { NAME: "Water", AMOUNT: "200 ml" }, + { NAME: "Sugar", AMOUNT: "275 g" }, + { NAME: "Whole cloves", AMOUNT: "5" }, + { NAME: "Cinnamon sticks", AMOUNT: "2" }, + { NAME: "Spice", AMOUNT: undefined }, + { NAME: "Bottle of red wine", AMOUNT: "1" }, + { NAME: "Raisins", AMOUNT: "100 g" }, + { NAME: "Slipped Almonds", AMOUNT: "50 g" }, + ], + description: "Mix everything, heat it, and you are good to go!", +}; +``` + +- [ ] Display a single recipe on the page using DOM manipulation. +- [ ] Implement a form to add a new recipe with a minimum of 5 ingredients. +- [ ] Optional: implement functionality to add a new ingredient to a recipe. + +--- + +### `JS2 week2` - Array functions, Arrow function + +Start with creating an array of recipe objects. Even a small one is perfectly enough, but go as big as you want! +Continue with the format of the recipe object you used last week or improve it and refactor! + +- [ ] Traverse through the array of recipe objects and display all the recipe cards in a grid. +- [ ] Implement functions to manipulate the array: +- find a recipe by a provided search word to check in the recipe title. +- sort the recipe array by the amount of ingredients needed. + +--- + +### `JS2 week3` - Callback function, Asynchronicity, Scope + +- [ ] Implement a cooking timer where the time is user-picked via an input or hard-coded. The timer should alert and/or ring once the time is up. +- [ ] Implement a timer for how much time you have spent on the page. + +--- + +### `JS3 week1` - Json, Apis, Fetch + +- [ ] Follow the [API creation guide](/homework-projects/guides/making-your-API-guide.md) to make your own API that you will use from now on. +- [ ] Refactor your code so that you ditch the static array of objects and instead fetch the recipes data from your API. +- [ ] Implement functionality to search for an ingredient, fetch and display the relevant ingredient prices for a recipe +- [ ] Ensure all the functionality is working smoothly after refactoring. + +--- + +### `JS3 week2` - Promises, Async/Await + +- [ ] You used promise chaining last week - now rewrite the fetch in the "async await" approach. +- [ ] Use the fuunctions created in preivous week and build functionality to: +- [ ] Find a recipe by a provided search word to check in the recipe title. +- [ ] Sort the recipe array by the amount of ingredients needed. + +--- + +### `JS3 week3` - Classes, Revision and Presentation of projects + +- [ ] Rest, revise JS fundamentals, finish, and brush up your project, prepare to present and explain it. +- [ ] Make improvements to the style or functionality or add additional functionality. +- [ ] Prepare to showcase your project to external people, talk through your code and explain what you have implemented. + + +--- + +
+
+ +## Project completion checklist ✅ + +- [ ] I can see a page with a list of recipes displayed in a grid; +- [ ] I can see the most important details about a recipe displayed in a nice and readable way; +- [ ] I can search for recipes by title, typing in a search keyword; +- [ ] I can sort the recipe array by the amount of ingredients needed; +- [ ] I can search for an ingredient, fetch and display the relevant ingredient prices for a recipe; +- [ ] I can use a cooking timer that alerts and/or rings once the time is up; +- [ ] I can see a timer for how much time I have spent on the page. diff --git a/homework-projects/readme.md b/homework-projects/readme.md new file mode 100644 index 00000000..68fe1daa --- /dev/null +++ b/homework-projects/readme.md @@ -0,0 +1,60 @@ +# WHAT + +During the JS2 and JS3 modules, you will be working on a project instead of the usual weekly homework assignments (which you can still do, as optional practice). Each week, you will be required to add new features to your project. By the end of JS3, you will have built an actual app using your newly gained knowledge and coding skills! +
+ +![](assets/project-flow.png) + +
+ +# WHY + +We're doing this for four main reasons: + +- You will gain experience and an understanding of what it's like to work on **one continuous project**, instead of switching contexts with each new homework assignment. +- You will apply what you learned every week and understand how each new method can be implemented into an actual product. +- You will build a solid project for your portfolio that you can showcase on your CV and in future tech interviews! +- You will gain experience presenting your project and code in a 'mini-tech interview' at the end of JS3. + +
+ +# PROJECT IDEAS + +[Currency Converter](projects/currency-converter/currency-converter.md)
+[Memory Game](projects/memory-game/memory-game.md)
+[Movie App](projects/movie-app/movie-app.md)
+[Quiz App](projects/quiz-app/quiz-app.md)
+[Recipe App](projects/recipe-app/recipe-app.md)
+ +> [!NOTE] +> New projects are welcome to be added by mentors. Just follow a similar structure to the existing ones, and submit it as a PR for review by staff and other mentors. + +
+ +# HOW + +The projects will either be worked on individually, in a pair or as a group. You may also be set up to peer review another's project. This is up to the staff and mentors running the module. + +
+ +First, you will pick a project idea from above. Each week, you will have specific tasks that you have to deliver. Those tasks are provided in your chosen project description. The tasks are designed to help you practice the main learning points throughout the JS2 and JS3 modules. + +
+ +You will work in your project repository for JS2 and JS3 (not the central homework repository!), and you will submit the weekly task in the usual way by creating a Pull Request. + +During JS2 and JS3, refer to the relevant [homework submission guide](guides/weekly-submission-guide.md). + +The main difference is that you will be on a different repository and that you will merge the PR after implementing the review-based improvements, while all the technical steps are the same as always. + +
+ +# DEPLOYMENT + +So you can demo your project easily both at the end of the project, but also to future employers, it is a requirement that you deploy the project. You can use the [HackYourFuture project template](https://github.com/HackYourFuture-CPH/hyf-project-template) as a starting point, or an otherwise agreed upon process by the staff and mentors. + +
+ +# CONCLUSION + +When you wrap up your project in JS3 week3, you will get a chance to present your project either as a video recording or on a demo day. If your team is hosting a demo day, then check out [this guide](guides/demo-day-presentation.md) for how to prepare for the presentation. diff --git a/javascript1/week1/assets/create-new-pull-request.png b/javascript1/week1/assets/create-new-pull-request.png new file mode 100644 index 00000000..8531ae73 Binary files /dev/null and b/javascript1/week1/assets/create-new-pull-request.png differ diff --git a/javascript1/week1/assets/merge-pull-request.png b/javascript1/week1/assets/merge-pull-request.png new file mode 100644 index 00000000..a94d07fc Binary files /dev/null and b/javascript1/week1/assets/merge-pull-request.png differ diff --git a/javascript1/week1/assets/open-a-pull-request.png b/javascript1/week1/assets/open-a-pull-request.png new file mode 100644 index 00000000..29cce5df Binary files /dev/null and b/javascript1/week1/assets/open-a-pull-request.png differ diff --git a/javascript1/week1/assets/pull-request-comment.png b/javascript1/week1/assets/pull-request-comment.png new file mode 100644 index 00000000..b94414d0 Binary files /dev/null and b/javascript1/week1/assets/pull-request-comment.png differ diff --git a/javascript1/week1/assets/pull-request-done.png b/javascript1/week1/assets/pull-request-done.png new file mode 100644 index 00000000..f00c34cb Binary files /dev/null and b/javascript1/week1/assets/pull-request-done.png differ diff --git a/javascript1/week1/homework.md b/javascript1/week1/homework.md index cc72f98d..ff6976d6 100644 --- a/javascript1/week1/homework.md +++ b/javascript1/week1/homework.md @@ -1,15 +1,48 @@ # Homework ![Hacking](https://media.giphy.com/media/eCqFYAVjjDksg/giphy.gif) + ## Step 1: Before you start with the homework: -1. Watch: What is programming Just watch the 2 min video, you do not have to do the entire JavaScript course (It could be useful later on though). + +1. Watch: What is programming Just watch the 2 min video, you do not have to do the entire JavaScript course (It could be useful later on though). + +### Get git ready to work on homework + +Using the ` your hyf-homework` repo. In the terminal run `git status` + +If there are changes that have not been committed, figure out what to do with those changes + +- Should they be committed to another branch? +- Should they be committed to `main`? +- Should they be discarded? + +When you have figured out what to do with the changes and fixed those. Write `git status` again. If it says `nothing to commit, working tree clean`. Then you are ready to create the branch for this weeks homework. + +#### Creating the branch + +Using the `your hyf-homework` repo write this command + +`git checkout main` - You are now on the `main` branch + +`git checkout -b javascript-javascript1-week1` + +This will create and checkout the branch so you are ready make commits to it + +[This video](https://www.youtube.com/watch?v=JcT4wmK1VcA) can help. On slack use the #git-support channel to ask questions about git ## Why should I do this homework? + > One must be able to crawl before understanding the true nature of Javascript - Albert Einstein This homework will get you started developing in javascript. What you learn the first 3 modules of javascript will be building blocks for creating great javascript web applications. +If you struggle to do this weeks homework there are a couple of things to do: + +- Watch the class recording. If it for some reason is missing. Then watch these: [part 1](https://www.youtube.com/watch?v=uhTRC33cpp0), [part 2](https://www.youtube.com/watch?v=mVgyjr9MV5U) +- Read up on javascript basics [here](readme.md#variables) + ## Step 2: Javascript warm up part one + Lets get started with some warm up exercises: On freeCodeCamp.com do the Basic JavaScript exercises up and until the **"Manipulate Arrays With push()"** exercise (there are some topics we did not cover but you can do it). Please add your freecodecamp username as answer for this exercise! @@ -17,40 +50,46 @@ Please add your freecodecamp username as answer for this exercise! You have finished the warmup exercises, well done! ## Step 3: Smart-ease - We help where we can + Enough warm up, lets get to the real problems! We will assume a real world business case where you (the developer) needs to help a business that is starting up (a startup) with solving some of their problems related to JavaScript! Here we go: --- Lets imagine that we have just started a cool new tech startup called **Smart-ease**. And lets imagine we even have this cool website url: `smart-ease.io` Now we are in business! -At **Smart-ease** we focus on solving real world problems. We venture into the world to help people, and by helping people, we create a sustainable business. +At **Smart-ease** we focus on solving real world problems. We venture into the world to help people, and by helping people, we create a sustainable business. Cool now lets venture into the world and see which problems we can solve with some of these cool products that Smart-ease will develop with your help: ![Adventure](https://media.giphy.com/media/oj2GhTqAIoNIk/giphy.gif) ### Age-ify (A future age calculator) + > You are talking to a friend who suddently looks at you and asks: "How old will you be in 2045?" Hmm you remember the year you were born and try to do some calculation: Born in 1987 + 3 that's 1990. 90 - 40 is 50 + 5 thats 58. I will be 58! Wow that was painful! Let's fix that by making some code that automatically does this! -Create two variables called `yearOfBirth` and `yearFuture`. Assign these your own age and a future year. -What type will these two variables be? Now calculate the age and store that in a variable called `age`. Log out this string: -"You will be 40 years old in 2027". With 40 being the result of the `age` variable and 2027 being the `yearFuture` variable. (Hint use string concatenation) +Create two variables called `yearOfBirth` and `yearFuture`. Assign these your birth year and a future year. +What type will these two variables be? Using `yearOfBirth` and `yearFuture` calculate the age and store that in a variable called `age`. + +Log out this string: "You will be 40 years old in 2027". With 40 being the result of the `age` variable and 2027 being the `yearFuture` variable. (Hint use string concatenation) ### Goodboy-Oldboy (A dog age calculator) + > The same friend (who by the way loves dogs) asks how old his dog will be in 2045. Hmm you think, lets make this into a product as well! -Dogs age can either be measured in dog years or in human years, this we want to take into consideration! +> Dogs age can either be measured in dog years or in human years, this we want to take into consideration! -Like before lets create three variables but this time we call them dogYearOfBirth, dogYearFuture and dogYear. We add an extra variable called shouldShowResultInDogYears. If it is true we should show the result in dog years, if it is false we should show it in human years. What do we call this type of variable? Now log this string out: +Like before lets create three variables but this time we call them `dogYearOfBirth`, `dogYearFuture` and `dogYear`. We add an extra variable called `shouldShowResultInDogYears`. If it is `true` we should show the result in dog years, if it is false we should show it in human years. What do we call this type of variable? Now dependent on `shouldShowResultInDogYears` log this string out: "Your dog will be 10 human years old in 2027" -or +or "Your dog will be 70 dog years old in 2027" ### Housey pricey (A house price estimator) + > Two of your friends are considering buying a house, but cannot figure out what the right price should be. Your friends know the width, the height and the depth of the house and the garden size. Lets help them figure out if they paid too much: We have made our own formula for calculating the price of a house. This formula is VERY simplified and not at all close to the real calculation which can get quite complicated: + ```js -housePrice = volumeInMeters * 2.5 * 1000 + gardenSizeInM2 * 300 +housePrice = volumeInMeters * 2.5 * 1000 + gardenSizeInM2 * 300; ``` Your friend Peter is considering a house that is 8m wide, 10m deep and 10m high. The garden size is 100m2. The house costs 2.500.000. @@ -58,34 +97,95 @@ Your friend Julia is considering a house that is 5m wide, 11m deep and 8m high. Figure out if Peter and Julia are paying too much or too little using Javascript and the formula specified above. -### Ez Namey (Startup name generator) *Optional* +### Ez Namey (Startup name generator) _Optional_ + > At a meetup you overhear a conversation between two developers. It went something like this: "Man i wish picking a startup name was easier! You need to be creative, funny and interesting, its nearly impossible!" Another problem to solve, awesome! Lets help people who struggle finding a startup name by creating some code! Create two arrays called `firstWords`, `secondWords`. The arrays should have 10 elements containing strings of possible startup names. Some examples could be: "Easy", "Awesome", "Corporate". -Create a variable called `startupName` that will contain created startup name. -Using a random index (you choose) of the arrays and concatenation of strings, create and log the new startup name and the number of characters in it. + +Create a variable called `startupName` that will contain the created startup name. + +Using a random index (you choose) of the arrays and concatenation of strings, create and log the new startup name and the number of characters in it. An example could be: "The startup: "Easy Corporation" contains 16 characters" Hint: you can use this code to generate a random number from 0-9, if you dont want to specify the indexes yourself. + ```js -const randomNumber = Math.floor(Math.random() * 10) + 0 +const randomNumber = Math.floor(Math.random() * 10); ``` + --- 4 projects from one startup, thats incredible! Lets hope one or more of these projects actually becomes popular! To be continued... - ## Step 4: Hand in Homework: -Steps: -* Use the ```hyf-homework``` repo and add your homework files in the ```javascript/javascript1/week1``` folder -* Make your commits for the homework. Remember to seperate the code into meaningful commits! -* Push the changes to github -* Share the github link to your classes slack channel. +We are going to be handing in homework using something called a **pull request (now PR)**. The reason for that is that **most companies use PR's** when they work with code. So you might aswell get used to it! + +Watch [this video](https://www.youtube.com/watch?v=JcT4wmK1VcA) to go through the same process as is documented here + +**Okay, lets go!** + +--- + +Use the `hyf-homework` repo and find the folder on your computer that contains this repo + +--- + +Using the branch called `javascript-javascript1-week1` + +--- + +To add your files go to the folder `javascript/javascript1/week1`. Here you **add all the files relevant for the homework**. Remember to **seperate the code into meaningful commits**. You can now push the commits + +``` +git add +git commit -m "Implemented task 1" +git push origin javascript-javascript1-week1 +``` + +--- + +Go into the ` your hyf-homework` repo on https://github.com/ click on the `Pull requests` tab and then click the `New pull request` button + +![Create new pull request](assets/create-new-pull-request.png) + +Where it says compare, choose the `javascript-javascript1-week1` branch. Just keep the PR title as it is (javascript-javascript1-week1). You can leave a comment if you want. Now click `Create pull request`. + +![Create new pull request](assets/open-a-pull-request.png) + +You have now handed in homework, but you are not quite done yet + +--- + +A mentor will look through your code and give you some feedback. + +![Pull request comment](assets/pull-request-comment.png) + +Based on the feedback, implement improvements to the homework. Then add, commit and push these improvements. + +``` +git add +git commit -m "Implemented feedback" +git push origin javascript-javascript1-week1 +``` + +--- + +Now you can merge the changes. Congrats, you are completely done with the homework 🎉🎉🎉 + +![Merge the pull request](assets/merge-pull-request.png) + +Now it should look like this: + +![Pull request done](assets/pull-request-done.png) + +When merged you can **share the github link** to your classes slack channel if you are **proud of what you did** 💪 + --- -And thats it your are done 🎉 +And thats it you are done 🎉 diff --git a/javascript1/week1/lesson-plan.md b/javascript1/week1/lesson-plan.md index e33248c6..f312a860 100644 --- a/javascript1/week1/lesson-plan.md +++ b/javascript1/week1/lesson-plan.md @@ -70,6 +70,12 @@ If you find anything that could be improved then please create a pull request! W - [Last exercise, pizza project](#pizza-project) +Here is a Notion Zoey Zou made: https://www.notion.so/JS1-Week1-2fdc88fdd4344c958091346efe3ba48b + +## Flipped classroom videos + +[Flipped classroom videos](https://github.com/HackYourFuture-CPH/JavaScript/blob/main/javascript1/week1/preparation.md#flipped-classroom-videos) + ## Code inspiration ### Variable types diff --git a/javascript1/week1/preparation.md b/javascript1/week1/preparation.md index a8f3ed66..679a6edc 100644 --- a/javascript1/week1/preparation.md +++ b/javascript1/week1/preparation.md @@ -1,8 +1,15 @@ ![Reading](https://media.giphy.com/media/l0MYtRl33WaN4HGBq/giphy.gif) # Preparation -- [ ] [Read this](http://speakingjs.com/es5/ch01.html) up to and including the *Strings* chapter (it’s okay if you don’t understand all of it yet, we will cover these concepts in class as well. Do make sure to write or document the questions you have so we can discuss them in class) (15 min) +- [ ] [Read this](https://exploringjs.com/es5/ch01.html) up to and including the *Strings* chapter (it’s okay if you don’t understand all of it yet, we will cover these concepts in class as well. Do make sure to write or document the questions you have so we can discuss them in class) (15 min) - [ ] [JavaScript Introduction at MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Introduction) (10 min) -_Please go through the material and come to class prepared!_ \ No newline at end of file +_Please go through the material and come to class prepared!_ + +## Flipped classroom videos +- [Javascript - data type](https://www.youtube.com/watch?v=tQByWsZeYrM) +- [Javascript - variables](https://www.youtube.com/watch?v=sfqt3ZotOhw) +- [Javascript - make variable names descriptive](https://www.youtube.com/watch?v=0bgIUXj5BF8) +- [Javascript - the subtle difference between let and var](https://www.youtube.com/watch?v=9yFx81K9b4k) +- [Javascript - operators and errors](https://www.youtube.com/watch?v=wVs6rzTReD8) diff --git a/javascript1/week1/readme.md b/javascript1/week1/readme.md index d3ab4fe7..c13d3436 100644 --- a/javascript1/week1/readme.md +++ b/javascript1/week1/readme.md @@ -89,7 +89,7 @@ However, in our communication, we will call these variables arrays. The values `null` and `undefined` are very similar in JavaScript, but they behave a bit differently. The difference is that `null` always has type "object", and `undefined` always has type "undefined". -Whenever you declare a variable, but you don't set a value, the variable will become `undefined`. JavaScript will never make a variable `null` unless you explicitly program it. +Whenever you declare a variable, but you don't set a value, the variable will become `undefined`. JavaScript will never make a variable `null` unless you explicitly program it - it represents the intentional absence of any object value (read [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/null) for more context). ```js let x; @@ -124,7 +124,7 @@ baz.length; //-> 11 ### String methods -> Todo +More about [string methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String). ## Number diff --git a/javascript1/week2/homework.md b/javascript1/week2/homework.md index 74a60cce..99a25b06 100644 --- a/javascript1/week2/homework.md +++ b/javascript1/week2/homework.md @@ -1,65 +1,103 @@ # Homework +### Get git ready to work on homework + +Using the `hyf-homework` repo. In the terminal run `git status` + +If there are changes that have not been committed, figure out what to do with those changes + +- Should they be committed to another branch? +- Should they be committed to `main`? +- Should they be discarded? + +When you have figured out what to do with the changes and fixed those. Write `git status` again. If it says `nothing to commit, working tree clean`. Then you are ready to create the branch for this weeks homework. + +#### Creating the branch + +Using the `hyf-homework` repo write this command + +`git checkout main` - You are now on the `main` branch + +`git checkout -b javascript-javascript1-week2` + +This will create and checkout the branch so you are ready make commits to it + +[This video](https://www.youtube.com/watch?v=JcT4wmK1VcA) can help. On slack use the #git-support channel to ask questions about git + ## Why should i even do this homework? + Functions and conditions are some of the basic building blocks of javascript. Functions ensure that we dont repeat ourselves when writing code. Conditions ensures that we can handle different cases when programming. +If you struggle to do this weeks homework there are a couple of things to do: + +- Watch the class recording. If it for some reason is missing. Then watch these: [part 1](https://www.youtube.com/watch?v=P9BQLgRm7zs), [part 2](https://www.youtube.com/watch?v=qFI5QnjN2GQ) +- Read up on javascript basics [here](readme.md#recap-logical-operators) + ## Javascript warmup + Just like last homework, lets **warmup our brain**! Do these freecodecamp challenges. We know this seems like a lot, but the tasks are not so big, so hang in there! If you get stuck on one of the tasks, just go to the next and then return to the difficult task later on. -- [ ] https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/passing-values-to-functions-with-arguments/ -- [ ] https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/return-a-value-from-a-function-with-return/ -- [ ] https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/assignment-with-a-returned-value/ -- [ ] https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/local-scope-and-functions/ -- [ ] https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/global-vs--local-scope-in-functions/ -- [ ] https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/introducing-else-if-statements/ -- [ ] https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/logical-order-in-if-else-statements/ -- [ ] https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-for-loops/ -- [ ] https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/iterate-through-an-array-with-a-for-loop/ +- [ ] [Passing values to functions with arguments](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/passing-values-to-functions-with-arguments/) +- [ ] [Return a value from a function with return](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/return-a-value-from-a-function-with-return/) +- [ ] [Assignment with a returned value](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/assignment-with-a-returned-value/) +- [ ] [Local scope and functions](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/local-scope-and-functions/) +- [ ] [Global vs local scope in functions](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/global-vs--local-scope-in-functions/) +- [ ] [Introducing else if statements](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/introducing-else-if-statements/) +- [ ] [Logical order in if else statements](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/logical-order-in-if-else-statements/) +- [ ] [Iterate with javascript for loops](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-for-loops/) +- [ ] [Iterate through an array with a for loop](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/iterate-through-an-array-with-a-for-loop/) Please add your freecodecamp username as answer for this exercise! --- ## Step 3: Smart-ease - Goes Global! -Following the massive success of Smart-ease's first couple of products things have been quite hectic at Smart-ease's shared office space. The phone is constantly ringing from journalists wanting to interview the genius behind the success and the greatest developers want to work for you. [Wired](www.wired.com) wrote an article with the headline "Smart-ease as good as Smarties" + +Following the massive success of Smart-ease's first couple of products things have been quite hectic at Smart-ease's shared office space. The phone is constantly ringing from journalists wanting to interview the genius behind the success and the greatest developers want to work for you. [Wired](https://www.wired.com) wrote an article with the headline "Smart-ease as good as Smarties" BUT people are asking: What will be the next product that truly defines Smart-ease as the startup of the century? ### Flight booking fullname function + Even for a startup as successful as Smart-ease there needs to be money in the bank. A customer from a flight booking website has asked for our help creating a specific part of their application: + When a user books a flight they **write their firstname and surname**, but when the ticket is printed a **fullname should be displayed**. It is our responsibility to create that. -Create a function called `getFullname` that returns a fullname. -It should have two parameters: `firstname` and `surname`. +Create a function called `getFullname` that returns a fullname. +It should have two parameters: `firstname` and `surname`. ```js -getFullname('Benjamin', 'Hughes'); // returns "Benjamin Hughes" +getFullname("Benjamin", "Hughes"); // returns "Benjamin Hughes" ``` -Now try to create two variables `fullname1` and `fullname2` these two variables should be assigned to the return of calling the `getFullname` function. +Now try to create two variables `fullname1` and `fullname2` these two variables should be assigned to calling the `getFullname` function. -Log out the two fullnames. +Log out the two fullname variables. #### Formal fullname -On the flight website the user has the possibility to **check a checkbox** that **indicates** if the user wants to be **adressed formally**. Lets also change `getFullname` to include support for formal name. -Create an extra parameter `useFormalName` that is a boolean. If it is true the function should add a `Lord` in front of the name. +On the flight website the user has the possibility to **check a checkbox** that **indicates** if the user wants to be **adressed formally**. Lets also change `getFullname` to include support for formal name. + +Create an extra parameter `useFormalName` that is a boolean. If it is true the function should add a `Lord` in front of the name. ```js -getFullname('Benjamin', 'Hughes', true); // returns "Lord Benjamin Hughes"` -getFullname('Benjamin', 'Hughes', false); // returns "Benjamin Hughes" +getFullname("Benjamin", "Hughes", true); // returns "Lord Benjamin Hughes"` +getFullname("Benjamin", "Hughes", false); // returns "Benjamin Hughes" ``` What do we do if `useFormalName` is not given as an argument? Remember to consider someone calling the function with an empty string as firstname and lastname. -Try out your code by pasting your getFullname function in the javascript part of this codepen: https://codepen.io/hackyourfuture-cph/pen/jJWwbN +Try out your code by pasting your `getFullname` function in the javascript part of this codepen: https://codepen.io/hackyourfuture-cph/pen/jJWwbN + +But what if the person is a woman? Describe how you would fix the `getFullname` so it also works for women ### Event application -Another customer has contacted us. He works for a secret company that rimes with foogle. The customer works on their calendar application. They need some functionality to help with writing what weekday an event is held. + +Another customer has contacted us. He works for a secret company that rimes with foogle. The customer works on their calendar application. They need some functionality to help with writing what weekday an event is held. You specify how many days from today an event is being held. The function then figures out what weekday the event is being held. Here is an example: @@ -73,11 +111,12 @@ console.log(getEventWeekday(9)); // Logs out "Thursday" console.log(getEventWeekday(2)); // Logs out "Sunday" ``` -You should get the today's day from the system. +You should get the today's day from the system. -Hint: use remainder operator, array indexes and investigate new Date in js. +Hint: use remainder operator, array indexes and investigate `new Date` in js. ### Weather wear + Create a function (that you have to name) that has temperature as parameter. Based on the temperature it should return a string with what the user should wear. You decide what the user should wear based on the temperature. An example is: @@ -90,93 +129,102 @@ console.log(clothesToWear); // Logs out: "shorts and a t-shirt" ![Wearing jackets](https://media.giphy.com/media/26u6dryuZH98z5KuY/giphy.gif) ### Student manager + A coding school have contacted us to make some functionality for managing their classes. We will create functionality for adding students to a class. -For this exercise you need to figure out how `Array.push` works. Learn about the concept by researching about it. +For this exercise you need to figure out how `Array.push` works. Learn about the concept by researching about it. Copy the following code into your homework js file + ```js const class07Students = []; function addStudentToClass(studentName) { - // You write code here + // You write code here } function getNumberOfStudents() { - // You write code here + // You write code here } ``` #### addStudentToClass function + The `addStudentToClass` should add the `studentName` to the `class07Students` array. But there are some other requirements: + - There can be only 6 students in a class. If more students are tried to be added, log out the following: "Cannot add more students to class 07". - The same person cannot be added to the class. If the same person is added to the class, log out the following: 'Student Benjamin is already in the class' where Benjamin is substituted for the `studentName`. - We are very fond of our Queen in Denmark, so if the Queen is added to the class she should always get a space. Even if the class has been filled out. - You cannot add an empty string to a class #### getNumberOfStudents function + `getNumberOfStudents` should simply return the number of students in the class. #### Now lets try and use the functions! + Try out all the cases: + - Add some students to the class. - Add more students than there is space for - Add a student that is already in the class - Add the Queen to a full class -- Call the `getNumberOfStudents` to log out the number of students. +- Call the `getNumberOfStudents` to log out the number of students. + +To see your code applied on a webapp, go here: https://codepen.io/hackyourfuture-cph/pen/PLPmOB and paste your javascript code. -To see your code applied on a webapp, go here: https://codepen.io/hackyourfuture-cph/pen/PLPmOB and paste your javascript code. +### Candy helper _optional_ -### Candy helper *optional* -> We are at the candystore. We have taken some shovels of the **caramel-strawberry-cola-lemon-gravy winegums**, a few of the **banana chocolate diesel-motors** and a handful of the **salmon-potato covered toffee encrusted pizzas**. But what is all this worth? And can you even afford it? +> We are at the candystore. We have taken some shovels of the **caramel-strawberry-cola-lemon-gravy winegums**, a few of the **banana chocolate diesel-motors** and a handful of the **salmon-potato covered toffee encrusted pizzas**. But what is all this worth? And can you even afford it? -Let's solve this problem with some functions. +Let's solve this problem with some functions. #### addCandy function + Create a function called `addCandy`. It has two parameters: + - `candyType` - specifies the candy type. Could be 'sweet, chocolate, toffee or chewing-gum' - `weight` - specifies the weigth of the candy in grams -The function should **add the price of the candy** to an array called `boughtCandyPrices` using [push](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) +The function should **add the price of the candy** to an array called `boughtCandyPrices` using [push](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) Here is an example of the usage: ```js -addCandy('sweet', 20); // Adds the price of 20 grams of sweets to the array boughtCandyPrices +addCandy("sweet", 20); // Adds the price of 20 grams of sweets to the array boughtCandyPrices ``` Candy table prices -| Candy type | Price per gram | -|-------------|----------------| -| Sweet | 0.5 | -| Chocolate | 0.7 | -| Toffee | 1.1 | -| Chewing-gum | 0.03 | - +| Candy type | Price per gram | +| ----------- | -------------- | +| Sweet | 0.5 | +| Chocolate | 0.7 | +| Toffee | 1.1 | +| Chewing-gum | 0.03 | #### Can i buy more? + Now create a variable called `amountToSpend` and assign it to `Math.random() * 100`. You can read about `Math.random` [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) -Create a new function called `canBuyMoreCandy`. This function returns a boolean indicating if the user can buy more candy using the `boughtCandy` array. +Create a new function called `canBuyMoreCandy`. This function returns a boolean indicating if the user can buy more candy using the `boughtCandy` array. Try use the function by adding some pieces of candy and checking if you can buy more. If the user can buy more candy the `console.log` the following: "You can buy more, so please do!". If the user cant buy more `console.log` the following: "Enough candy for you!" -Hint: Use a for loop to calculate the total price of the candy pieces. +Hint: Use a for loop to calculate the total price of the candy pieces. -*Optional* Use a [while loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while) instead of a for loop. +_Optional_ Use a [while loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while) instead of a for loop. +## Step 4: Hand in Homework: -## Step 4: Rover the Robot *Optional* -Go and try out this cool game: [roverjs.com](http://roverjs.com), written by one of the HYF teachers from Amsterdam, [Joost Lubach](https://github.com/joost). There are different levels. Solve the chapter up until and including the variables chapter. - -## Step 5: Hand in Homework: -Steps: -* Use the ```hyf-homework``` repo and add your homework files in the ```javascript/javascript1/week2``` folder -* Make your commits for the homework. Remember to seperate the code into meaningful commits! -* Push the changes to github -* Share the github link to your classes slack channel. ---- +Watch [this video](https://www.youtube.com/watch?v=JcT4wmK1VcA) for a more detailed go-through of how to hand in homework! -And thats it your are done 🎉 +- Use the branch called `javascript-javascript1-week2` +- Add all your changes to this branch in the `javascript-javascript1-week2` folder. +- Create a pull request using the `javascript-javascript1-week2` branch and give your PR the same name `javascript-javascript1-week2` +- Wait for mentor feedback +- Implement feedback, `add`, `commit` and `push` the changes +- Now you can merge the changes into `main` +- When merged you can **share the github link** to your classes slack channel if you are **proud of what you did** 💪 +- Now celebrate 🎉🎉🎉 diff --git a/javascript1/week2/lesson-plan.md b/javascript1/week2/lesson-plan.md index 7d719299..2390d2d7 100644 --- a/javascript1/week2/lesson-plan.md +++ b/javascript1/week2/lesson-plan.md @@ -20,7 +20,7 @@ If you find anything that could be improved then please create a pull request! W - Conditions - [Code inspiration](#if-sentences) - [Exercises](#if-sentences-1) -- Functions +- Functions (https://twitter.com/wesbos/status/1105907924088565762) - General description - A function is a reusable piece of code. - Function usage - Arguments @@ -44,6 +44,13 @@ If you find anything that could be improved then please create a pull request! W The students really struggle with the **return** value. What it means, how it is captured. What happens when nothing is returned etc. Try really hammering in this concept with lots of simple examples and exercises! Fx if a function is called get something. That means that something is returned from that function. +Zoey Zou made a nice Notion lesson plan here: https://www.notion.so/JS1-Week2-8f2d4b7e7ba0425ea4a9e97816e9ceb7 + + +## Flipped classroom videos + +[Flipped classroom videos](https://github.com/HackYourFuture-CPH/JavaScript/blob/main/javascript1/week2/preparation.md#flipped-classroom-videos) + ## Code inspiration ### If sentences @@ -137,7 +144,7 @@ function multiply(a, b) { return a * b; } -multiply(10 * 4); +multiply(10, 4); // Return value function sum(a, b) { @@ -238,10 +245,10 @@ console.log(spam(14) === 'huehuehuehuehuehuehuehuehuehuehuehuehuehue') ### If sentences Create an `if` sentence that will give a user a message based on his bank account balance. Use the `balance` variable and change that. -- If a user has less that 0 log out 'Please earn some money!' -- If a user has between 0 and 1000 log out 'Your balance is looking okay' -- If a user has between 1000 and 3000 log out 'Your balance is looking good' -- If a user has between 3000 and 10000 log out 'Your balance is fantastic' +- If a user has 0 or less balance log out 'Please deposit some money!' +- If a user has more than 0 and at most 1000 log out 'Your balance is looking okay' +- If a user has more than 1000 and at most 3000 log out 'Your balance is looking good' +- If a user has more than 3000 and at most 10000 log out 'Your balance is fantastic' - If a user has more than 10000 log out 'Your balance is AMAZING!' ```js diff --git a/javascript1/week2/preparation.md b/javascript1/week2/preparation.md index 266b442b..c0f7f032 100644 --- a/javascript1/week2/preparation.md +++ b/javascript1/week2/preparation.md @@ -7,3 +7,9 @@ ![Cosy rain](https://media.giphy.com/media/k28n1OPefBEeQ/giphy.gif) _Please go through the material and come to class prepared!_ + +## Flipped classroom videos +- [Javascript conditions](https://www.loom.com/share/6affdcf03b4f43ceac56424ff04975e5) +- [Javascript loops](https://www.loom.com/share/4663f4fa5c784fff9ab67f2b91166c9b) +- [Javascript function](https://www.loom.com/share/61fadf80906d481497e3b40273897d20) +- [Javascript scope](https://www.loom.com/share/b8874230724040598860e8f059d8e369) diff --git a/javascript1/week2/readme.md b/javascript1/week2/readme.md index f23fa17f..f741bc21 100644 --- a/javascript1/week2/readme.md +++ b/javascript1/week2/readme.md @@ -32,7 +32,7 @@ Teaching note. Start off explaining functions with how to use a function fx expl |0|0|1| |1|1|1| -So you can say that false in combination with `&&` always returns true +So you can say that false in combination with `&&` always returns false ```js true && false //-> false false && true //-> false diff --git a/javascript1/week3/homework.md b/javascript1/week3/homework.md index 065ae450..ca56812d 100644 --- a/javascript1/week3/homework.md +++ b/javascript1/week3/homework.md @@ -1,27 +1,22 @@ # Homework ## Why should i even do this homework? + Array's has lots of helper functions, that is used all the time when developing js applications. It is super helpful to be able to **manipulate an array** like **removing elements** or **adding elements** at specific indexes. Another helpful function of arrays is to know **where a specific item is** in the array. Objects can be used for **representing data** and it can **help structure your code**. An object can fx represent a user that has a firstname, surname, profile picture and a list of friends. It is constantly used in javascript and **essential to learning the language**. +If you struggle to do this weeks homework there are a couple of things to do: + +- Watch the class recording. If it for some reason is missing. Then watch these: [part 1](https://www.youtube.com/watch?v=idfGCqAItGI), [part 2](https://www.youtube.com/watch?v=cNRFY0RW5L8) +- Read up on objects and arrays [here](readme.md#objects) + ## Javascript warmup Its warmup time! ![Warm up](https://media.giphy.com/media/Cfw4WE617UgUw/giphy.gif) -### Freecodecamp exercises - -- [ ] https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/build-javascript-objects/ -- [ ] https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-dot-notation/ -- [ ] https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-bracket-notation/ -- [ ] https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/updating-object-properties/ -- [ ] https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/add-new-properties-to-a-javascript-object/ -- [ ] https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/using-objects-for-lookups/ - -Please add your freecodecamp username as answer for this exercise! ---- ### Item array removal @@ -30,9 +25,17 @@ Remove the item in `names` that is equal to `nameToRemove` Copy the code below to your homework ```js - -const names = ['Peter', 'Ahmad', 'Yana', 'kristina', 'Rasmus', 'Samuel', 'katrine', 'Tala']; -const nameToRemove = 'Ahmad'; +const names = [ + "Peter", + "Ahmad", + "Yana", + "kristina", + "Rasmus", + "Samuel", + "katrine", + "Tala", +]; +const nameToRemove = "Ahmad"; // Write some code here @@ -43,11 +46,11 @@ console.log(names); // ['Peter', 'Yana', 'kristina', 'Rasmus', 'Samuel', 'katrin --- - ### When will we be there?? + Write a function where you speficy your speed in `km/h` and how far you have to go in `km`. The function has to return the time it will take to arrive at your destination. The time should be formatted like this: `3 hours and 34 minutes`. -*Hint:* For formatting your best friend is Google! +_Hint:_ For formatting your best friend is Google! ```js const travelInformation = { @@ -56,7 +59,7 @@ const travelInformation = { }; const travelTime = notThisFunctionName(travelInformation); -console.log(travelTime); // 4 hours and 42 minutes +console.log(travelTime); // 8 hours and 38 minutes ``` --- @@ -66,31 +69,31 @@ console.log(travelTime); // 4 hours and 42 minutes ```js const seriesDurations = [ { - title: 'Game of thrones', + title: "Game of thrones", days: 3, hours: 1, - minutes: 0, + minutes: 0, }, { - title: 'Sopranos', + title: "Sopranos", days: 3, hours: 14, minutes: 0, }, { - title: 'The Wire', + title: "The Wire", days: 2, hours: 12, minutes: 0, - } -] + }, +]; ``` -How much time of my life have i been watching series? Lets find out! Calculate **how much time a series** have taken as a **percentage of an average lifespan** of 80 years. +How much time of my life have i been watching series on tv? Lets find out! Calculate **how much time a tv series** have taken as a **percentage of an average lifespan** of 80 years. -Firstly change the `seriesDurations` object to include your favorite series. Find the duration of a series here: http://tiii.me/ +Firstly change the `seriesDurations` array found above to include your favorite series. Find the duration of a series here: http://tiii.me/ -Using the `seriesDurations` log out the text: +Create a function that logs out the following text using the `seriesDurations` array: ``` Game of thrones took 0.01% of my life @@ -100,139 +103,114 @@ The Wire took 0.007% of my life In total that is 0.2% of my life ``` -### My favorite songs - -Lets create some js where you can add songs from a list of available songs to your own list of songs you like. +Here is an example: ```js -const songDatabase = [{ - songId: 1, - title: 'My baby', - artist: 'Soggy socks', - }, - { - songId: 2, - title: '3 nails in wood', - artist: 'The carpenters', - }, - { - songId: 3, - title: 'Blacker than black', - artist: 'Instant coffee', - }, +const seriesDurations = [ { - songId: 4, - title: 'When is enough too little?', - artist: 'The spies girls', + title: "Game of thrones", + days: 3, + hours: 1, + minutes: 0, }, ]; -const myPlaylist = []; -``` - -> In this task when i mention a song i mean an `object` that is represented as a song. You can also say that a song is represented **as an** object - -#### Add song to database -Lets create a function that can **add a song** to the `songDatabase` array. +function logOutSeriesText() { + // write code here +} -The function should be called `addSongToDatabase` and have one parameter called `song`. The type of `song` should be an object with the same keys as the songs in the `songDatabase` array. +logOutSeriesText(); // logs out the text found above +``` -Now **add some of your favorite songs to the database** using `addSongToDatabase`. +## Smart-ease - Back to the basics! -Now a question for you! Should this function return anything? What do you think, why/why not? +Smart-ease is going back to the basics. As always Smart-ease starts by helping people fix their problems. So lets venture out into the real world and see what we find: -#### Searching for a song -Create a function called `getSongByTitle` that returns the songs that match a song title. It has one parameter called `title`. It should return -the song that match the `title` parameter. +### NOnoN0nOYes (Note taking app) -Lets give an example: +> You are sitting at a meeting. A person is presenting some interesting thought that you want to write down. You check your bag, but realise that you forgot to bring your notepad. Hmm you check the internet for an online solution. But you need to signup for them all, too bad... Maybe this could be a worthwhile problem so solve. Lets create a simple and easy to use notepad 📝 -```js -const searchedSong = getSongByTitle('When is enough too little?'); -console.log(searchedSong); // returns { songId: 4, title: 'When is enough too little', artist: 'The spies girls'} +#### Save a note -const searchedSong2 = getSongByTitle('When is enough too'); -console.log(searchedSong); // returns undefined -``` +The first thing we will create is the functionality to **save a note**: +Create a variable called `notes` and assign it to an empty array. +Create a function called `saveNote`. The `saveNote` has two parameters: -Try to use the function by searching for some different songs that are in the `songDatabase` and some that are not. +- `content` parameter is a string. +- `id` is a number. -*Hint:* First find the index of the object in the `songDatabase` array where the title match, then return that index of the `songDatabase` array. +The `saveNote` function should push an object to the `notes` array with the keys `content` and `id`. Here is an example -*Optional:* Add fuzzy search, so we can search for "When enough to little?" and still get the song with id 4. +```js +const notes = []; -#### Create our own playlist -Lets use the two functions we have created to **make our own playlist!** -Create a new function called `addSongToMyPlaylist` it has a parameter called `title`. +function saveNote(content, id) { + // write some code here +} -Using the `getSongByTitle` and the `addSong` functions create a function where you specify the song title of the song you would like in your playlist! +saveNote("Pick up groceries", 1); +saveNote("Do laundry", 2); -Here is an example: - -```js -addSongToMyPlaylist('3 nails in wood'); -console.log(myPlaylist); // [{ songId: 2, title: '3 nails in wood', artist: 'The carpenters' }] +console.log(notes); // [{content: 'Pick up groceries', id: 1}, {content: 'Do laundry', id: 2}] ``` -Use this function to add some songs to your playlist! - -#### Improving our application *optional* -What if there are multiple songs with the same name? Then we have problems in our `getSongByTitle` function! Instead of returning a song, return an array of songs that match the title parameter. - -What if a user had multiple playlists? How could we accomodate that? Either describe how to fix this problem or make some code! +#### Get a note -![boombox](https://media.giphy.com/media/NkkKrHU2wAin6/giphy.gif) +**Now a user can save a note**, but what if a user wants to **see a specific note**, but only remembers the id? Lets create that functionality for him: +Create a function called `getNote`. The function has one parameter called `id`. When calling this function with an id it should return the relevant note object that corresponds to the id. If no id is specified or if the id is not a number, log out an error string. +Hint: Use a for loop. -## Step 3: Smart-ease - Back to the basics! -Smart-ease is going back to the basics. As always Smart-ease starts by helping people fix their problems. So lets venture out into the real world and see what we find: +```js +function getNote(id) { + // your code here +} -### NOnoN0nOYes (Note taking app) -> You are sitting at a meeting. A person is presenting some interesting thought that you want to write down. You check your bag, but realise that you forgot to bring your notepad. Hmm you check the internet for an online solution. But you need to signup for them all, too bad... Maybe this could be a worthwhile problem so solve. Lets create a simple and easy to use notepad 📝 +const firstNote = getNote(1); +console.log(firstNote); // {content: 'Pick up groceries', id: 1} +``` -#### Save a note -The first thing we will create is the functionality to **save a note**: -Create a variable called `notes` and assign it to an empty array. -Create a function called `addNote`. The `addNote` has two parameters: -- `content` parameter is a string. -- `id` is a number. +#### Log out notes -The `addNote` function shall push an object to the notes array. This object has two keys: `content` and `id`, that corresponds to the function parameters. The value of the keys should be the value of the corresponding parameters. +Now a user can both save and get a note. What if the user just wants to **read all his notes?** Lets also create that functionality: +Create a function `logOutNotesFormatted`. When calling the function it should log this string out for every note: +"The note with id: 1, has the following note text: "some example note"." -#### Get a note -**Now a user can add a note**, but what if a user wants to **see a specific note**, but only remembers the id? Lets create that functionality for him: -Create a function called `getNoteFromId`. The function has one parameter called `id`. When calling this function with an id it should return the relevant note object that corresponds to the id. If no id is specified or if the id is not a number, log out an error string. -Hint: Use a for loop. +```js +function logOutNotesFormatted() { + // your code here +} -#### Get all notes -Should return an array of the notes. +logOutNotesFormatted(); // should log out the text below -#### Log out notes -Now a user can both add and get a note. What if the user just wants to **read all his notes?** Lets also create that functionality: -Create a function `logOutNotesFormatted`. When calling the function it should log this string out for every note: -"The note with id: 1, has the following note text: "some example note"." +// The note with id: 1, has the following note text: Pick up groceries +// The note with id: 2, has the following note text: Do laundry +``` #### Unique feature -Suddenly you get this great idea for making the note app even better! + +Suddenly you get this great idea for making the note app even better! Come up with a unique feature **you think would make this app better.** Write down the idea and see if you can implement it. If not dont worry :) If it is too hard to implement try and ask in the slack channel :) -Try an **interactive version 💻 of your code** [here](https://codepen.io/hackyourfuture-cph/pen/GeMzdE). Remember to insert your code in the top of the codepen :) +Try an **interactive version 💻 of your code** [here](https://codepen.io/dalsHughes/pen/poJGejX). Remember to insert your code in the top of the codepen :) + +### CactusIO-interactive (Smart phone usage app) _optional_ -### CactusIO-interactive (Smart phone usage app) *optional* > After a long day you come home to relax. The first thing you do is find your phone and start watching some youtube. Then check facebook, and then reading some news. Suddently a hour has passed. What happened to all that time you think to yourself. Maybe we can create some program to help with this problem! What if we could help users manage their smart phone usage? -Its going to work like this: A user can add smartphone activities. Then he can see a status on how his smartphone usage is going. +Its going to work like this: A user can add smartphone activities. Then he can see a status on how his smartphone usage is going. #### Adding an activity + Lets create the first part of the functionality that is **adding activities.** Create a variable called `activities` that stores all activities of the day. What type of variable would you think would make sense? -Create a function called `addActivity`. It should have three parameters: `date`, `activity` and `duration`. The `date` should be a string, the `activity` a string and the `duration` a number. To save the activity push an object that contains the date, the activity and the duration to the activities variable. +Create a function called `addActivity`. It should have three parameters: `date`, `activity` and `duration`. The `date` should be a string, the `activity` a string and the `duration` a number. To save the activity push an object that contains the date, the activity and the duration to the activities variable. Now a user can add an activity by writing: ```js -addActivity('23/7-18', 'Youtube', 30); +addActivity("23/7-18", "Youtube", 30); /* activities should now look like this @@ -247,50 +225,42 @@ activities should now look like this Just adding activities wont help the user very much, we need to **add some functionality** to show the user how **his smart phone usage is going.** #### Show my status + Create a function called `showStatus`. This function should use the activities variable and return a string saying the following: "You have added 3 activities. They amount to 78 min. of usage" + ```js showStatus(activities); // will log out this "You have added 3 activities. They amount to 78 min. of usage" ``` + Now what happens if we call `showStatus` and `activities` is empty? We need to take that into consideration: If `activities` is empty log out a string that says: "Add some activities before calling showStatus" #### Usage limit -A user asks us if it is possible to **set a limit for his smartphone usage.** "Off course it is" we promptly reply! + +A user asks us if it is possible to **set a limit for his smartphone usage.** "Off course it is" we promptly reply! We need to store that limit somewhere, but where and what type should this be? So how should it work? When `showStatus` is called and the users usage is above the limit he set. Log out the following string: "You have reached your limit, no more smartphoning for you!" Try and add some activities and call `showStatus` #### Extra feature + Come up with one feature you think would be helpful for this program. Optional -* Lets improve the `addActivity`, so that we dont need to specify the date, but the function automatically figures out what the date is. Check out this link: https://stackoverflow.com/a/34015511 -* Improve the `showStatus` function by only showing the number of actitivies for that specific day. -* Create a function for calculating the activity a user has spent the most time on. ---- +- Lets improve the `addActivity`, so that we dont need to specify the date, but the function automatically figures out what the date is. Check out this link: https://stackoverflow.com/a/34015511 +- Improve the `showStatus` function by only showing the number of actitivies for that specific day. +- Create a function for calculating the activity a user has spent the most time on. -## Step 4 bonus homework -the Bonus homework for this week (for those of you want an extra challenge) do the following: - -Go to http://roverjs.com/ and complete the functions and arrays chapters. - -## Step 5: Hand in Homework: -Go over your homework one last time: +--- -- Does every file run without errors and with the correct results? -- Have you used `const` and `let` and avoided `var`? -- Do the variable, function and argument names you created follow the [Naming Conventions](https://github.com/HackYourFuture/fundamentals/blob/master/fundamentals/naming_conventions.md)? -- Is your code well-formatted (see [Code Formatting](https://github.com/HackYourFuture/fundamentals/blob/master/fundamentals/naming_conventions.md))? +## Bonus homework -If you can answer yes to the above questions then you are ready to hand if the homework: +The bonus homework for this week (for those of you want an extra challenge) do the following: -* Use the `hyf-homework` repo and add your homework files in the `javascript/javascript1/week3` folder -* Make your commits for the homework. Remember to seperate the code into meaningful commits! -* Push the changes to github -* Share the github link to your classes slack channel. +https://www.codewars.com/kata/job-matching-number-1/train/javascript
+https://www.codewars.com/kata/job-matching-number-2/train/javascript
+https://www.codewars.com/kata/unfinished-loop-bug-fixing-number-1/train/javascript
---- -🎉 diff --git a/javascript1/week3/lesson-plan.md b/javascript1/week3/lesson-plan.md index b3cc15a3..dd4e23dc 100644 --- a/javascript1/week3/lesson-plan.md +++ b/javascript1/week3/lesson-plan.md @@ -1,4 +1,5 @@ # Lesson plan + ``` > Focus on having lots of in class exercises. @@ -16,21 +17,22 @@ To find examples of what teachers have taught before go to the class branches in If you find anything that could be improved then please create a pull request! We welcome changes, so please get involved if you have any ideas!!! --- + - Objects - - Access properties two ways: .keyname and [keyname] - - Key - value - - Array of objects - - Let the students explain iterating an array of objects - - Use real world examples (users, products, houselistings) - - [Code inspiration](#objects) + - Access properties two ways: .keyname and [keyname] + - Key - value + - Array of objects + - Let the students explain iterating an array of objects + - Use real world examples (users, products, houselistings) + - [Code inspiration](#objects) - Arrays continued - - `Pop`, `push`, `shift`, `unshift` - - Let students investigate `shift` and `unshift` - - The longest of the word pairs unshift, push makes the array longer! - - `includes` - Let the students investigate this - - Looping through an array - - No `forEach`, `map`, `filter` or `reduce` - - [Code inspiration](#arrays) + - `Pop`, `push`, `shift`, `unshift` + - Let students investigate `shift` and `unshift` + - The longest of the word pairs unshift, push makes the array longer! + - `includes` - Let the students investigate this + - Looping through an array + - No `forEach`, `map`, `filter` or `reduce` + - [Code inspiration](#arrays) - [Codewar exercises](#codewar-exercises) - Call stack - Used for figuring code flow in js! Where does my function go when it is done here. @@ -38,74 +40,81 @@ If you find anything that could be improved then please create a pull request! W - [Code inspiration](#call-stack) - [Exercise](#call-stack-1) +Zoey Zou has created a nice lesson plan here: https://www.notion.so/JS1-Week3-a0f122866ac34fc3b98b7a41870046f4 + +## Flipped classroom videos + +[Flipped classroom videos](https://github.com/HackYourFuture-CPH/JavaScript/blob/main/javascript1/week3/preparation.md#flipped-classroom-videos) + ## Code inspiration ### Objects + ```js const user = { - name: 'Emil', + name: "Emil", age: 25, - role: 'Teacher', - classes: ['Javascript 1', 'Javascript 2'], + role: "Teacher", + classes: ["Javascript 1", "Javascript 2"], hobbies: { - favourite: 'computers', - sports: 'running to class' - } -} + favourite: "computers", + sports: "running to class", + }, +}; -console.log(user) +console.log(user); // Add new property -user.lastname = 'Bay' +user.lastname = "Bay"; -console.log(user) +console.log(user); -delete user.lastname +delete user.lastname; -console.log(user) +console.log(user); -console.log(user.hobbies.favourite) -console.log({ favourite: 'computers', sports: 'running to class' }.favourite) +console.log(user.hobbies.favourite); +console.log({ favourite: "computers", sports: "running to class" }.favourite); -function graduatedClass (student, className) { - if (student.classes.includes(className)) return 'Error' +function graduatedClass(student, className) { + if (student.classes.includes(className)) return "Error"; - student.classes.push(className) + student.classes.push(className); } -console.log(user) -graduatedClass(user, 'HTML') -console.log(user) -graduatedClass(user, 'HTML') +console.log(user); +graduatedClass(user, "HTML"); +console.log(user); +graduatedClass(user, "HTML"); const newUser = { - name: '', - age: '' -} + name: "", + age: "", +}; +var students = []; function addStudent(student) { - if (student.name == null && typeof student.name === 'string') return 'Error' - if (student.age == null) return 'Error' + if (student.name == null && typeof student.name === "string") return "Error"; + if (student.age == null) return "Error"; - students.push(student) + students.push(student); } -addStudent({ name: 'Rahim' }) -console.log(students) +addStudent({ name: "Rahim" }); +console.log(students); // ways to access properties -user.name -user['name'] +user.name; +user["name"]; -const prop = 'name' -user[prop] +const prop = "name"; +user[prop]; -user['name'] = 'Maria' -user[0] = 'Hello world' - -console.log(user) +user["name"] = "Maria"; +user[0] = "Hello world"; +console.log(user); ``` ### Arrays @@ -113,110 +122,98 @@ console.log(user) ```js // one way to have multiple data about a student is with an array // for each piece of data -const studentNames = [ - 'Fowad', - 'Emil', - 'Zoey' -] +const studentNames = ["Fowad", "Emil", "Zoey"]; -const studentAges = [ - 32, - 25, - 28 -] +const studentAges = [32, 25, 28]; -console.log(studentNames) -console.log(studentAges) +console.log(studentNames); +console.log(studentAges); // Another, more ergonomic way is with objects const students = [ - { name: 'Fowad', age: 32 }, - { name: 'Emil', age: 25, teacher: true }, - { name: 'Zoey', age: 28 } -] + { name: "Fowad", age: 32 }, + { name: "Emil", age: 25, teacher: true }, + { name: "Zoey", age: 28 }, +]; -console.log(students) +console.log(students); // We can access properties with `.` -console.log(students[0].name) +console.log(students[0].name); -for(let i = 0; i < students.length; i++) { +for (let i = 0; i < students.length; i++) { const currentStudent = students[i]; console.log(typeof currentStudent); console.log(currentStudent.name); } -students.push({ name: 'Ahmad', age: 27 }); +students.push({ name: "Ahmad", age: 27 }); // One object that we have seen before const Math = { random: function () { - return 42 + return 42; }, - round: function (x) { - } -} - + round: function (x) {}, +}; ``` - ### Call stack + ```js function a() { - // add to call stack - b(); + // add to call stack + b(); - return 'a'; - // remove from call stack + return "a"; + // remove from call stack } - function b() { - //throw 'hello'; - return 'b'; + //throw 'hello'; + return "b"; } a(); - ``` - ## Exercises ## Call stack Draw the call stack array at every draw point + ```js function bookPlaneTickets() { - // draw - console.log('Plane tickets booked'); - requestVacationDays(); - // draw + // draw + console.log("Plane tickets booked"); + requestVacationDays(); + // draw } - function bookHotel() { - console.log('Hotel booked'); - // draw - planItinerary(); - // draw +function bookHotel() { + console.log("Hotel booked"); + // draw + planItinerary(); + // draw } function requestVacationDays() { - // draw - console.log('Vacation days requested'); - // draw + // draw + console.log("Vacation days requested"); + // draw } function planItinerary() { - console.log('Itinerary done'); - // draw + console.log("Itinerary done"); + // draw } function planTrip() { - bookPlaneTickets(); - // draw - bookHotel(); - // draw - console.log('Trip planned'); + bookPlaneTickets(); + // draw + bookHotel(); + // draw + console.log("Trip planned"); } // draw planTrip(); @@ -224,13 +221,10 @@ planTrip(); ``` ### Codewar exercises + - [CodeWars - Add property to every object](https://www.codewars.com/kata/add-property-to-every-object-in-array/train/javascript) -- [CodeWars - Job Matching 1](https://www.codewars.com/kata/job-matching-number-1/train/javascript) -- [CodeWars - Who's Online](https://www.codewars.com/kata/whos-online/train/javascript) -- [CodeWars - Ironman Triathlon](https://www.codewars.com/kata/ironman-triathlon/train/javascript) -- [CodeWars - Job Matching 2](https://www.codewars.com/kata/job-matching-number-2/train/javascript) - [CodeWars - Color Association](https://www.codewars.com/kata/colour-association/train/javascript) - [CodeWars - Unfinished loop](https://www.codewars.com/kata/unfinished-loop-bug-fixing-number-1/train/javascript) - [CodeWars - Is this my tail](https://www.codewars.com/kata/is-this-my-tail/train/javascript) - [CodeWars - Longest word](https://www.codewars.com/kata/squash-the-bugs/train/javascript) -- BONUS [CodeWars - Super Duper Easy](https://www.codewars.com/kata/super-duper-easy/train/javascript) \ No newline at end of file +- [CodeWars - Who's Online](https://www.codewars.com/kata/whos-online/train/javascript) diff --git a/javascript1/week3/preparation.md b/javascript1/week3/preparation.md index 09fa134f..fe659f19 100644 --- a/javascript1/week3/preparation.md +++ b/javascript1/week3/preparation.md @@ -4,3 +4,9 @@ - [Objects](http://javascript.info/object) (15 min) _Please go through the material and come to class prepared!_ + +## Flipped classroom videos + +- [Javascript callstack](https://www.loom.com/share/d09d10ea84da45e2bddd9ffa05396ed3) +- [Javascript objects](https://www.loom.com/share/312a9ec3e2ed42beb6017f4a4167bd46) +- [Javascript array](https://www.loom.com/share/06cdd6a4a3834cb696db8dd941ea6550) diff --git a/javascript1/week4/homework.md b/javascript1/week4/homework.md index c425af65..952a8790 100644 --- a/javascript1/week4/homework.md +++ b/javascript1/week4/homework.md @@ -1,17 +1,36 @@ # Homework ## Why should i even do this homework? -Understanding the basics of Javascript is SUPER important. Therefore this homework focuses on repeating the basics to really have a solid understanding of this. + +Understanding the basics of Javascript is SUPER important. Therefore this homework focuses on repeating the basics to really have a solid understanding of this. + +If you struggle to do this weeks homework there are a couple of things to do: + +- Watch the class recording. If it for some reason is missing. Then watch these: [part 1](https://www.youtube.com/watch?v=Mo54btMPN7Q), [part 2](https://www.youtube.com/watch?v=mSUAoual5sE), [part 3](https://www.youtube.com/watch?v=uq3NnTtXqsU) +- Go through the last 3 weeks readme files. [Week 1](../week1/readme.md#variables), [week 2](../week2/readme.md#recap-logical-operators), [week 3](../week3/readme.md#objects) ## Finishing class exercises -Finish the exercises from the class + +Finish the exercises from the class! + +## Codewars + + +Complete these Katas in codewars:
+- [7kyu Vowel Count](https://www.codewars.com/kata/54ff3102c1bad923760001f3)
+- [7kyu Digit*Digit](https://www.codewars.com/kata/546e2562b03326a88e000020)
+- [7kyu Highest and Lowest](https://www.codewars.com/kata/554b4ac871d6813a03000035)
+ +Post a link to your codewars profile when you sumbmit the homework! ## Voice assistant + You will be building a voice assistant 🤖! Is that even possible in javascript, YES! EVERYTHING is possible in javascript 💪 (nearly) Create a function called `getReply(command)`. The function should return a response that corresponds to the command! These are the commands you should be able to give the voice assistant: + - `Hello my name is Benjamin` - Should save the name benjamin. and respond with "nice to meet you Benjamin". What if someone writes this twice? - `What is my name` - should respond with the name of the person. What if the name has not yet been mentioned? - `Add fishing to my todo` - Should respond with "fishing added to your todo". Should add fishing to a list of todos @@ -20,41 +39,29 @@ These are the commands you should be able to give the voice assistant: - `What is on my todo?` - should respond with the todos. Fx you have 2 todos - fishing and singing in the shower - `What day is it today?` - Should respond with the date in a human readable format. E.g. if today is 30/8/2019 then it should respond with 30. of August 2019 - Should be able to do simple math. fx `what is 3 + 3` should respond with 6. Or `what is 4 * 12` should respond with 48 -- `My favorite dish is lasagne` - should save the user's favorite dish as lasagne. -- `What is my favorite dish` - should respond with the favorite dish - `Set a timer for 4 minutes` - Should respond with "Timer set for 4 minutes". When 4 minutes is up: "Timer done". How do we set a timer in js? Google is your friend here! -- `Add Bike ride the 3/5/2019 to my calendar` - Should respond with "Bike ride added to your calendar". Should add an event represented by an object with keys `name` and `date` to an array of events. -- `What am I doing this week?` - should respond with the events for that week. Fx "This week you have 1 event: Bike ride the 3. of May 2019" - Add one or more command to your voice assistant Here is an example of usage: ```js -console.log(getReply('Hello my name is Benjamin')); // "Nice to meet you benjamin" -console.log(getReply('What is my name?')); // "Your name is Benjamin" -console.log(getReply('Add Bike ride the 3/5-2019 to my calendar')); // "Bike ride added to your calendar" +console.log(getReply("Hello my name is Benjamin")); // "Nice to meet you benjamin" +console.log(getReply("What is my name?")); // "Your name is Benjamin" +console.log(getReply("Add fishing to my todo")); // "fishing added to your todo" ``` -When you are done, add your `getReply` function and global variables to this CodeSandbox and try the voice command out with both commands and speech! +When you are done, add your `getReply` function and global variables to this CodeSandbox and try the voice command out with both commands and speech! ---> https://codesandbox.io/s/beautiful-worker-gnhbw <--- -## Hand in Homework: -Go over your homework one last time: +## Homework checklist -- Does every file run without errors and with the correct results? -- Have you used `const` and `let` and avoided `var`? -- Do the variable, function and argument names you created follow the [Naming Conventions](https://github.com/HackYourFuture/fundamentals/blob/master/fundamentals/naming_conventions.md)? -- Is your code well-formatted (see [Code Formatting](https://github.com/HackYourFuture/fundamentals/blob/master/fundamentals/naming_conventions.md))? - -If you can answer yes to the above questions then you are ready to hand in the homework: - -* Use the `hyf-homework` repo and add your homework files in the `javascript/javascript1/week4` folder -* Make your commits for the homework. Remember to separate the code into meaningful commits! -* Push the changes to Github -* Share the Github link to your class' slack channel. +Go over your homework one last time: ---- +- [ ] Does every file run without errors and with the correct results? +- [ ] Have you used `const` and `let` and avoided `var`? +- [ ] Do the variable, function and argument names you created follow the [Naming Conventions](https://github.com/HackYourFuture/fundamentals/blob/master/fundamentals/naming_conventions.md)? +- [ ] Is your code well-formatted (see [Code Formatting](https://github.com/HackYourFuture/fundamentals/blob/master/fundamentals/code_formatting.md))? -🎉 + Please, fill out the [survey](https://forms.gle/QKTWFbUTkzgdcKiMA) about the module to give feedback to the staff, teachers and homework helpers. diff --git a/javascript1/week4/lesson-plan.md b/javascript1/week4/lesson-plan.md index e0d4e855..30a6bbba 100644 --- a/javascript1/week4/lesson-plan.md +++ b/javascript1/week4/lesson-plan.md @@ -38,6 +38,11 @@ Focus on - Letting the students learn a framework for solving problems - Lots and lost of exercises 💪 +## Typical misconceptions + +- Difference between return and console.log +- What console.log does and what it is made for + ## Code inspiration ### Fibonacci Sequence @@ -234,3 +239,5 @@ Try and make the game playable! *optional* ### Conway's game of life *optional* https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life + +And finally, feel free to fill out the form to help us improve the module and the exercises. The [survey](https://forms.gle/irckYkBdvSb6Tdz57) here is addressed to the teacher and teacher assistant, while this [survey](https://forms.gle/ttdDLcSJ88ksz6xe7) is for homework helpers. diff --git a/javascript2/readme.md b/javascript2/readme.md index 89e2563c..6cff4a2c 100644 --- a/javascript2/readme.md +++ b/javascript2/readme.md @@ -2,6 +2,6 @@ | Week | Topic | Preparation | Homework | Lesson plan | | ---- | ----- | ----------- | -------- |------------ | -| 4. | Browser environment
DOM manipulation
DOM event listeners | [Preparation](week1/preparation.md) | [Homework](week1/homework.md) | [Lesson plan](week1/lesson-plan.md)| -| 5. | Array functions
[Arrow function](week2/readme.md#arrow-function) | [Preparation](week2/preparation.md) | [Homework](week2/homework.md) | [Lesson plan](week2/lesson-plan.md)| -| 6. | Callback function
Asyncronicity
Scope | [Preparation](week3/preparation.md) | [Homework](week3/homework.md) | [Lesson plan](week3/lesson-plan.md)| +| 1. | Browser environment
DOM manipulation
DOM event listeners | [Preparation](week1/preparation.md) | [Homework](/homework-projects/readme.md) | [Lesson plan](week1/lesson-plan.md)| +| 2. | Array functions
[Arrow function](week2/readme.md#arrow-function) | [Preparation](week2/preparation.md) | [Homework](/homework-projects/readme.md) | [Lesson plan](week2/lesson-plan.md)| +| 3. | Callback function
Asyncronicity
Scope | [Preparation](week3/preparation.md) | [Homework](/homework-projects/readme.md) | [Lesson plan](week3/lesson-plan.md)| diff --git a/javascript2/week1/homework.md b/javascript2/week1/homework.md deleted file mode 100644 index ad1c3abc..00000000 --- a/javascript2/week1/homework.md +++ /dev/null @@ -1,185 +0,0 @@ -# Homework - -## So why this homework? -**Interacting with the DOM is a crucial part** of building a website. If we cannot interact with the DOM and the javascript we write cannot be used in a browser. **Connecting javascript to the browser opens up a new world of possibilities** where only the imagination is the limiting factor. - -## Problem solving cardio -Lets exercise our problem solving abilities! - -![mind exercise](https://media.giphy.com/media/l41m04gr7tRet7Uas/giphy.gif) - -### Find the shortest word -Write a function that finds the shortest word of an array of words - -```js -const danishWords = ['bil', 'plante', 'kaffe', 'bog', 'ø', 'planetarium']; -notThisFunctionName(danishWords); // returns 'ø' -``` - -### Difference between median and average -Understand the **difference between average and median** by: -- Make a function that takes an array as parameter and returns the average of that parameter -- Make a function that takes an array as parameter and returns the median of that parameter - -Now create a function that calculates the median and the average and returns these two value in an object. - -```js -// use the functions on this array -const housePrices = [3000000, 3500000, 1300000, 40000000, 100000000, 8000000, 2100000]; -``` - -Now render the prices and the average and median in a web page. - - -## Spirit animal name generator -Let's create a page where **a user writes his name** in an input element. The user then clicks a button. The user will now **receive a spirit animal name**, fx Benjamin - The fullmoon wolf. - -### Markup time! -Create an input element, a button and a tag to display the spirit animal into. - -### Setting up the events -When the user clicks the button, get the name the user wrote in the input field. - -### Spirit animal part -Now we can get the users name, next step is to **add the spirit animal string** and display that the users name, a dash and then the spirit animal. Fx Name: Peter: Peter - The crying butterfly -For creating the spirit animal create an array with 10 string representing spirit animals. Now get a random item in the array that will represent the spirit animal. - -### New spirit animal -Now a user tells us that he wants a new spirit animal. No problem we say. Let's create functionality where a user can press a button and then get a new spirit animal. - -### No input -What if the user clicks the generate new spirit animal and there is no text in the input? - -### Event types - *Optional and a little tricky* -Give the user the possibility to select **when the spirit animal should be created**. Should it be when the user clicks the button or when the user hovers the input field or when text is written in the input field? - -How can we give a user multiple options to select from in html? Maybe time for google! - -An example is: A user select that she only wants to generate a spirit animal when the input is hovered. That means that if the user writes her name in the input and clicks the button nothing happens. BUT when she hovers the input, NOW a new spirit animal is generated. - -![Spiritanimal](https://media.giphy.com/media/IMSq59ySKydYQ/giphy.gif) - - -## hyfBay - get the okay'est products here -We have been **hired for a company** to do a SPA - Single Page App for them. It is a website where a user can search for products. The products can also be **filtered and sorted** based on what products the user wants to see. - -We are going to be building this website step by step, so have patience :) - -### Lets get started! -In the [homework/hyf-bay folder](homework/hyf-bay) there is a project you should continue working on. So copy all the files into your hyf-homework/Javascript/javascript2/week1 folder. - -Open the `index.html` file in a browser and take a look at the site and the html by inspecting the website. - -I have done some rudimentary styling for the project but you are super welcome to make it even nicer! - -So the site looks like a typical product site, but is **missing some products!** Lets fix that! - -#### Render test product names -Create an array called `testProductNames` that contains test product names. Lets start of with taking this array of test product names and render them! - -To render these test products, we need to do the following: -1. Select the `ul` that is a child to the `section` called `products` in javascript -2. For each `productName` in the `testProductNames`: - 1. [create an `li`](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement) - 2. Set the innerHTML of that `li` to the `productName` - 3. [Append the `li`](https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild) to the `ul` - -#### Render products function -When test products can be rendered, lets create a function that does the this! - -So lets create a function called `renderProducts`. It has one parameter: `products` - which is an array. - -It should work like this: -```js -const testProductNames = ['Flat screen', 'Mobile phone', 'Wallet']; -renderProducts(testProductNames); // Should add 3 li's to the ul under the products section with Flat screen, Mobile phone, Wallet text -``` - -We have now made a **code abstraction**, awesome! When we want to render new products, we dont need to think about all the details of innerHtml, appendChild etc, we simply need to call the `renderProducts` function with an array we would like to render. - -#### Improving the `renderProducts` function -Now representing a product by **ONLY its name is a bit too simple.** A product usually has a price, a rating, a specific id, a name and countries it ships to. If we have to represent a product with that kind of data in Javascript we use an `object` with the following keys: `id`, `name`, `price`, `rating`, `shipsTo`. In the `main.js` file there is a function available to you called `getAvailableProducts`. **Calling this function** will return an **array of products.** There can be from 0 - 30 products in the array. - -```js -const products = getAvailableProducts(); -console.log(products) // logs out -/* -[{ - id: 23771823, - name: 'Flat screen', - price: 4000, - rating: 4.2, - shipsTo: [ 'denmark', 'germany'], -}, -...] -*/ -``` - -Lets improve the `renderProducts` so that it still shows only product names, but using the `products` from calling `getAvailableProducts`! - -#### Showing more details to the user -So now we have come a long way. We can get `products` calling `getAvailableProducts`. Those `product` names we can render by calling `renderProducts(products)`. But now the **user also wants to see the price, the rating and where the product ships to.** Lets first implement it in a simple way: - -Lets seperate the different product details with a `|`. So calling `renderProducts(products)` will now add an `li` with the `innerHTML` that looks like this: `Flat screen | 4000 | 4.2 | [ 'denmark', 'germany']` - -That is all fine and dandy and it kind of works, BUT we would of course like to improve it. - -#### Showing more details to the user in a nice way! -We could see all the product details as a **list of product details!** How do we represent lists in html?? - -Yes, thats right with a `ul` and `li` tag. So each product detail is an `li` inside a `ul`. - -Now we have two sets of `ul` and `li` tags. We have the individual products and then for every product we have the individual product details. - -#### *Optional* ships to rendering. -A product can be **shipped to multiple countries**, that means that it can be seen as a list of countries. How do we represent lists in html?? - -I think you know the answer! Try and implement ships to so it is represented as a list in html. - -A product li should now look like this: - -```html -
  • -
      -
    • Drone
    • -
    • 1234
    • -
    • 5
    • -
    • -
        -
      • Denmark
      • -
      • Sweden
      • -
      -
    • -
    -
  • -``` - -We have now made a fully functioning website that can render products. For the next homework we are **going to improve the site further.** - -## Feedback giving time! -Find a student to give feedback using this site: https://hyf-peer-review.herokuapp.com/ -The feedback should be given after the homework has been handed in, preferably the latest two days after. - -To help you get started we have created some resources about giving feedback. Find them here: https://github.com/HackYourFuture-CPH/curriculum/tree/master/review - - -## Hand in Homework: -Go over your homework one last time: - -- Does every file run without errors and with the correct results? -- Have you used `const` and `let` and avoided `var`? -- Do the variable, function and argument names you created follow the [Naming Conventions](https://github.com/HackYourFuture/fundamentals/blob/master/fundamentals/naming_conventions.md)? -- Is your code well-formatted (see [Code Formatting](https://github.com/HackYourFuture/fundamentals/blob/master/fundamentals/naming_conventions.md))? - -![check](https://media.giphy.com/media/l4EpblDY4msVtKAOk/giphy.gif) - -If you can answer yes to the above questions then you are ready to hand if the homework: - -- Use the `hyf-homework` repo and add your homework files in the `javascript/javascript2/week1` folder -- Make your commits for the homework. Remember to seperate the code into meaningful commits! -- Push the changes to github -- To finish the homework post the link for your repo and the rendered index.html on your classes slack channel - ---- - -🎉 diff --git a/javascript2/week1/homework/hyf-bay/hyfBayHelpers.js b/javascript2/week1/homework/hyf-bay/hyfBayHelpers.js deleted file mode 100644 index c80de6d2..00000000 --- a/javascript2/week1/homework/hyf-bay/hyfBayHelpers.js +++ /dev/null @@ -1,68 +0,0 @@ -/* DONT MODIFY ANY OF THIS CODE!!!*/ - -window.getAvailableProducts = function() { - function getRandomInt(min, max) { - min = Math.ceil(min); - max = Math.floor(max); - return Math.floor(Math.random() * (max - min + 1)) + min; - } - - function getRandomItem(availableProductNames) { - return availableProductNames[getRandomInt(0, availableProductNames.length - 1)]; - } - - function getRandomProductname() { - const preWords = ['Used', 'Fantastic', '"Used"', 'Broken', 'Beautiful', 'Wet', 'Green', 'Sloppy', 'Dirty']; - const productNames = ['Carrot', 'Drone', 'Giftcard', 'Puppy', 'Car', 'Shirt', 'Milk', 'Chalk', 'Fish fingers', 'Socks', 'Chocolate', 'Toothbrush', 'Computer', 'Nokia', 'Cologne']; - - let chosenProductName = getRandomItem(productNames); - const shouldHavePreWord = getRandomInt(0, 10) > 6; - - if (shouldHavePreWord) { - const preWord = preWords[getRandomInt(0, preWords.length - 1)]; - chosenProductName = `${preWord} ${chosenProductName}`; - } - - return chosenProductName; - } - - /* DONT MODIFY ANY OF THIS CODE!!!*/ - function getRandomCountries() { - const availableCountries = ['Denmark', 'Sweden', 'Norway', 'Germany', 'Iceland', 'England']; - const numberOfCountries = getRandomInt(1, 3); - - const randomCountries = []; - while (randomCountries.length < numberOfCountries) { - const randomIndex = getRandomInt(0, availableCountries.length - 1); - const randomCountry = availableCountries[randomIndex]; - if(!randomCountries.includes(randomCountry)) { - randomCountries.push(randomCountry); - } - } - - return randomCountries; - } - - const numberOfAvailableProducts = getRandomInt(0, 30); - const availableProducts = Array.apply(null, Array(numberOfAvailableProducts)) - .map(() => { - const name = getRandomProductname(); - return { - id: `${name}${getRandomInt(0, 100000)}`, - name, - price: getRandomInt(0, 10000), - rating: getRandomInt(1, 10), - shipsTo: getRandomCountries(), - }; - }); - - return availableProducts; -} - -window.sendPricesToServer = function(prices, callback) { - console.log(`Sending these prices: ${prices} to an analytics server`); - - setTimeout(() => { - callback(`These prices were received ${prices}`); - }, 3000) -} \ No newline at end of file diff --git a/javascript2/week1/homework/hyf-bay/index.html b/javascript2/week1/homework/hyf-bay/index.html deleted file mode 100644 index 29526c25..00000000 --- a/javascript2/week1/homework/hyf-bay/index.html +++ /dev/null @@ -1,59 +0,0 @@ - - Codestin Search App - - - - - -
    -
    -
    -

    HyfBay

    -

    - Buy the okay'est products

    -
    -
    -
    - -
    - - -
    -
    -
    - - -
    -
    - - -
    -
    -
    -
    -
      -
      -
      -

      Your shopping cart

      -
      -

      Total price:

      -
      -
        -
        -
        - - - \ No newline at end of file diff --git a/javascript2/week1/homework/hyf-bay/main.js b/javascript2/week1/homework/hyf-bay/main.js deleted file mode 100644 index f97e04eb..00000000 --- a/javascript2/week1/homework/hyf-bay/main.js +++ /dev/null @@ -1,3 +0,0 @@ -console.log('Script loaded'); - -console.log(getAvailableProducts()); diff --git a/javascript2/week1/lesson-plan.md b/javascript2/week1/lesson-plan.md index 03db8eba..0c7ea406 100644 --- a/javascript2/week1/lesson-plan.md +++ b/javascript2/week1/lesson-plan.md @@ -21,16 +21,19 @@ If you find anything that could be improved then please create a pull request! W - HTML vs CSS vs JS - Client vs server - Where is the script tag being loaded - -- DOM manipulation - - Get elements - - Create elements - - Insert elements - let students investigate `appendChild`, `insertBefore` - - Element manipulation (`style`, `innerHTML`, `text`) - - Document object - - [Code inspiration simple](#dom) - - [Code inspiration change logo](#change-logo) - - Exercises: [Favorite dishes](#favorite-dishes), [podcasts](#podcast), [image inserter](#image-inserter) + - Code debugging + +- DOM + - What is it and what do developers use the DOM for? + - DOM manipulation + - Get elements + - Create elements + - Insert elements - let students investigate `appendChild`, `insertBefore` + - Element manipulation (`style`, `innerHTML`, `text`) + - Document object + - [Code inspiration simple](#dom) + - [Code inspiration change logo](#change-logo) + - Exercises: [Favorite dishes](#favorite-dishes), [podcasts](#podcast), [image inserter](#image-inserter) - Event listeners - Focus on usage, no explanation of callback - Click, mouseover, etc. Explain one and let students investigate another, like mouseover or mousemove @@ -42,6 +45,10 @@ If you find anything that could be improved then please create a pull request! W Really try in this class to do short teaching and lots of exercises! +## Flipped classroom videos + +[Flipped classroom videos](https://github.com/HackYourFuture-CPH/JavaScript/blob/main/javascript2/week1/preparation.md#flipped-classroom-videos) + ## Code inspiration ### DOM @@ -121,14 +128,14 @@ const podcasts = [{ 3. For every podast: 1. Creat an `li` 2. Create an `h1` element - 3. Change the innerHTML of hte `h1` to equal the name of the current podcast + 3. Change the innerHTML of the `h1` to equal the name of the current podcast 4. Append the `h1` to the `li` 5. Now add an image to the `li` with the `src` set to the `imageUrl`. But only if the `imageUrl` key exists on the object! 4. Append the `li` to the `ul` ### Image inserter -Create a function that has two parameters: `imageUrl` and `elementToAppendImageTo`. The function should create a img tag using the `imageUrl` parameter. The function should then append the `img` to the `elementToAppendImageTo` - html element. +Create a function that has two parameters: `imageUrl` and `elementToAppendImageTo`. The function should create an img tag and set the `src` attribute of the img to the `imageUrl` parameter. The function should then append the `img` to the `elementToAppendImageTo` - html element. ```js // Should append a img tag to the body with the picture from 'https://picsum.photos/536/354' @@ -143,4 +150,4 @@ When clicking a button, change the text on the button to say "Button clicked" Clicking a button should toggle the background color of the body and the text color in the page. If the background is white and the text is black, then clicking the button will make the background dark and the text white and vice versa -*Optional* also make the text on the button change. \ No newline at end of file +*Optional* also make the text on the button change. diff --git a/javascript2/week1/optional-homework.md b/javascript2/week1/optional-homework.md new file mode 100644 index 00000000..de25854b --- /dev/null +++ b/javascript2/week1/optional-homework.md @@ -0,0 +1,115 @@ +> [!WARNING] +> These are optional homework exercises that you can complete on top of your [homework project](/homework-projects/readme.md), if you wish. There is no requirement for these to be reviewed, but feel free to ask a mentor if you wish for some feedback. + +# Optional Homework + +## So why this homework? + +**Interacting with the DOM is a crucial part** of building a website. If we cannot interact with the DOM then the javascript we write cannot change what we see in the browser. **Connecting javascript to the browser opens up a new world of possibilities** where only the imagination is the limiting factor. + +## Overview of homework + +# 1. Problem solving cardio + +Lets exercise our problem solving abilities! + +![mind exercise](https://media.giphy.com/media/l41m04gr7tRet7Uas/giphy.gif) + +## 1.1. codewars! + +Complete these Katas: +- [8kyu Remove First and Last Character](https://www.codewars.com/kata/56bc28ad5bdaeb48760009b0) +- [8kyu Counting sheep...](https://www.codewars.com/kata/54edbc7200b811e956000556) +- [7kyu String ends with?](https://www.codewars.com/kata/51f2d1cafc9c0f745c00037d) +- [7kyu Odd or Even?](https://www.codewars.com/kata/5949481f86420f59480000e7) + +## 1.2. Find and count the Danish letters + +Find the individual number and the total number of Danish letters in a string. + +```js +const danishString = "Jeg har en blå bil"; +notThisFunctionName(danishString); // returns {total: 1, å: 1} + +const danishString2 = "Blå grød med røde bær"; +notThisFunctionName(danishString2); // returns {total: 4, æ: 1, ø: 2, å: 1} +``` + +# 2. Spirit animal name generator + +Let's create a page where **a user writes his name** in an input element. The user then clicks a button. The user will now **receive a spirit animal name**, fx Benjamin - The fullmoon wolf. + +## 2.1. Markup time! + +Create an input element, a button and a tag to display the spirit animal into. + +## 2.2. Setting up the events + +When the user clicks the button, get the name the user wrote in the input field. + +## 2.3. Spirit animal part + +Now we can get the users name, next step is to **add the spirit animal string** and display that the users name, a dash and then the spirit animal. Fx Name: Peter: Peter - The crying butterfly +For creating the spirit animal create an array with 10 string representing spirit animals. Now get a random item in the array that will represent the spirit animal. + +## 2.4. New spirit animal + +Now a user tells us that he wants a new spirit animal. No problem we say. Let's create functionality where a user can press a button and then get a new spirit animal. + +## 2.5. No input + +What if the user clicks the generate new spirit animal and there is no text in the input? + +## 2.6. Event types - _Optional and a little tricky_ + +Give the user the possibility to select **when the spirit animal should be created**. Should it be when the user clicks the button or when the user hovers the input field or when text is written in the input field? + +How can we give a user multiple options to select from in html? Maybe time for google! + +An example is: A user select that she only wants to generate a spirit animal when the input is hovered. That means that if the user writes her name in the input and clicks the button nothing happens. BUT when she hovers the input, NOW a new spirit animal is generated. + +![Spiritanimal](https://media.giphy.com/media/IMSq59ySKydYQ/giphy.gif) + +# 3. hyfBay - get the okay'est products here + +We have been **hired for a company** to do a SPA - Single Page App for them. It is a website where a user can search for products. The products can also be **filtered and sorted** based on what products the user wants to see. + +We are going to be building this website step by step, so have patience :) + +## 3.1. Lets get started! + +In the [homework/hyf-bay folder](homework/hyf-bay) there is a project template you should continue working on. So copy all the files into your `hyf-homework/javascript/javascript2/week1` folder. + +The `index.html` is very basic. It simply loads two javascript files and include some css. The two javascript files are `hyfBayHelpers.js` and the `main.js`. `hyfBayHelpers.js` contains a function (`getAvailableProducts`) that we can use to get an array of products. In the `main.js` we will be writing all our code! + +## 3.2. Requirements + +- Using the `getAvailableProducts` array we will render an html list of products +- The list should contain `title`, `price` and `rating` +- The list of products should be generated through calling a function called `renderProducts(products)` + +### Example + +```js +const products = getAvailableProducts(); + +function renderProducts(products) { + // your code here +} + +renderProducts(products); // This should create the ul and the li's with the individual products details +``` + +So after calling the `renderProducts` function, the output should be like the output you can see here: https://codesandbox.io/s/hyf-bay-first-week-oml13 + +### So how can I do that? + +Here is a possible way to render the products + +1. In the html create a `ul` that will contain all the products. Select that `ul` using `document.querySelector` +2. For each `product` in the `products` array: + 1. [create an `li`](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement) + 2. Set the innerHTML of that `li` to the contain the title, price and rating + 3. [Append the `li`](https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild) to the `ul` + +
        diff --git a/javascript2/week1/optional-homework/hyf-bay/hyfBayHelpers.js b/javascript2/week1/optional-homework/hyf-bay/hyfBayHelpers.js new file mode 100644 index 00000000..a216cfa1 --- /dev/null +++ b/javascript2/week1/optional-homework/hyf-bay/hyfBayHelpers.js @@ -0,0 +1,72 @@ +/* DONT MODIFY ANY OF THIS CODE!!!*/ + +window.getAvailableProducts = function() { + function getRandomInt(min, max) { + min = Math.ceil(min); + max = Math.floor(max); + return Math.floor(Math.random() * (max - min + 1)) + min; + } + + function getRandomItem(availableProductNames) { + return availableProductNames[ + getRandomInt(0, availableProductNames.length - 1) + ]; + } + + function getRandomProductname() { + const preWords = [ + "Used", + "Fantastic", + '"Used"', + "Broken", + "Beautiful", + "Wet", + "Green", + "Sloppy", + "Dirty" + ]; + const productNames = [ + "Carrot", + "Drone", + "Giftcard", + "Puppy", + "Car", + "Shirt", + "Milk", + "Chalk", + "Fish fingers", + "Socks", + "Chocolate", + "Toothbrush", + "Computer", + "Nokia", + "Cologne" + ]; + + let chosenProductName = getRandomItem(productNames); + const shouldHavePreWord = getRandomInt(0, 10) > 6; + + if (shouldHavePreWord) { + const preWord = preWords[getRandomInt(0, preWords.length - 1)]; + chosenProductName = `${preWord} ${chosenProductName}`; + } + + return chosenProductName; + } + + const numberOfAvailableProducts = getRandomInt(0, 30); + const availableProducts = Array.apply( + null, + Array(numberOfAvailableProducts) + ).map(() => { + const name = getRandomProductname(); + return { + id: `${name}${getRandomInt(0, 100000)}`, + name, + price: getRandomInt(0, 10000), + rating: getRandomInt(1, 10) + }; + }); + + return availableProducts; +}; diff --git a/javascript2/week1/optional-homework/hyf-bay/index.html b/javascript2/week1/optional-homework/hyf-bay/index.html new file mode 100644 index 00000000..07f60fe4 --- /dev/null +++ b/javascript2/week1/optional-homework/hyf-bay/index.html @@ -0,0 +1,14 @@ + + Codestin Search App + + + + + +
        + + + diff --git a/javascript2/week1/optional-homework/hyf-bay/main.css b/javascript2/week1/optional-homework/hyf-bay/main.css new file mode 100644 index 00000000..60af4201 --- /dev/null +++ b/javascript2/week1/optional-homework/hyf-bay/main.css @@ -0,0 +1,18 @@ +body { + font-family: "Open Sans", sans-serif; + background-color: #F9FBFD; +} + +* { + box-sizing: border-box; +} + +body, h1, h2 { + margin: 0; +} + +ul { + list-style-type: none; + margin: 0; + padding: 0; +} diff --git a/javascript2/week1/optional-homework/hyf-bay/main.js b/javascript2/week1/optional-homework/hyf-bay/main.js new file mode 100644 index 00000000..e584d34c --- /dev/null +++ b/javascript2/week1/optional-homework/hyf-bay/main.js @@ -0,0 +1,4 @@ +console.log("Script loaded"); + +const products = getAvailableProducts(); +console.log(products); diff --git a/javascript2/week1/preparation.md b/javascript2/week1/preparation.md index 14e32cf1..741fd49c 100644 --- a/javascript2/week1/preparation.md +++ b/javascript2/week1/preparation.md @@ -6,3 +6,8 @@ - [Attaching an event](https://www.w3schools.com/jsref/met_element_addeventlistener.asp) (5 min) _Please go through the material and come to class prepared!_ + +## Flipped classroom videos +- [Executing Javascript in the browser environment](https://youtu.be/k8PEyCe3vK0) +- [Interacting with the DOM using Javascript](https://youtu.be/YvHQIaKtOl8) +- [DOM event listeners using Javascript](https://youtu.be/DwzApTvTngI) diff --git a/javascript2/week1/readme.md b/javascript2/week1/readme.md index 18634373..3886978c 100644 --- a/javascript2/week1/readme.md +++ b/javascript2/week1/readme.md @@ -4,12 +4,14 @@ Browser environment - [ ] Client vs server - [ ] Where is the script tag being loaded -DOM manipulation -- [ ] Get elements -- [ ] Insert elements -- [ ] Element manipulation (style, innerHTML, text) -- [ ] Window object -- [ ] Document object +DOM +- [ ] What is it and what do developers use the DOM for? +- [ ] DOM manipulation + - [ ] Get elements + - [ ] Insert elements + - [ ] Element manipulation (style, innerHTML, text) + - [ ] Window object + - [ ] Document object Event listeners - [ ] Document onload @@ -17,7 +19,7 @@ Event listeners ## Relevant links * [Preparation](preparation.md) -* [Homework](homework.md) +* [Homework](/homework-projects/readme.md) * [Lesson plan](lesson-plan.md) diff --git a/javascript2/week2/homework.md b/javascript2/week2/homework.md deleted file mode 100644 index 4e88260f..00000000 --- a/javascript2/week2/homework.md +++ /dev/null @@ -1,121 +0,0 @@ -# Homework - -## Why should i even do this homework? -Working with arrays is an essential part of being a javascript developer. A lot of the time js developers have an array of some objects. That could be **users, products, posts, jobs** etc. Working with these arrays, js developers so often need to filter the arrays, change the structure of the array, sort them or loop through them. - -On top of that combining these array function with each other will show the functional side to javascript in a nice way. - -The warmup exercises will be a bit abstract. But the in the **hyfBay exercise** the task will be a lot closer to a **real world task**. - -## Warmup array exercises - -### Doubling of number -Say you would like to write a program that **doubles the odd numbers** in an array and **throws away the even number**. - -Your solution could be something like this: -```js -let numbers = [1, 2, 3, 4]; -let newNumbers = []; - -for(let i = 0; i < numbers.length; i++) { - if(numbers[i] % 2 !== 0) { - newNumbers[i] = numbers[i] * 2; - } -} - -console.log("The doubled numbers are", newNumbers); // [2, 6] -``` - -Rewrite the above program using `map` and `filter` don't forget to use arrow functions. - -### Working with movies -![cinema](https://media.giphy.com/media/l6mBchxYZc7Sw/giphy.gif) - -Copy the movies array in the [movies](homework/movies.js) file. Use this array to do the following tasks: -1. Create an array of movies containing the **movies with a short title** (you define what short means) -2. Create an array of movie titles with **long movie titles** -3. Count the **number of movies** made between 1980-1989 (including both the years) -4. Create a new array that has an **extra key called tag**. The tag is based on the rating: Good (>= 7), Average (>= 4 and < 7), Bad (< 4) -5. **Using [chaining](readme.md#Chaining)**, first filter the movies array to only contain the movies rated higher than 6. Now map the movies array to only the rating of the movies. -6. **Count the total number of movies** containing any of following keywords: `Surfer`, `Alien` or `Benjamin`. So if there were 3 movies that contained `Surfer`, 1 with `Alien` and 2 with `Benjamin`, you would return 6. Can you make sure the search is case insensitive? -7. Create an array of movies where a **word in the title is duplicated**. Fx "Star **Wars**: The Clone **Wars**" the word **Wars** is duplicated. -8. Find the word that is **mostly duplicated** using [sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) *Optional* -9. Calculate the **average rating** of all the movies using [reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce). *Optional* -10. **Count the total number** of Good, Average and Bad movies using [reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce). *Optional* - - -## hyfBay - get the okay'est products here - continued -**Continue work on your homework regarding the Hyfbay** from previous week. Please copy the files from last week into this weeks hyf-homework folder and continue working there. If you have not made last weeks homework the solution for it is included in [this weeks homework folder](homework/hyf-bay) in the main.js file. - -### Filter products -A very normal usecase for a product site it that a **user wants to search for some product** or get products that only ships to his country. Lets implement that functionality for a user! - -BUT first lets figure out what happens on a conceptual level: -1. Some kind of **event happens**, fx a user searches for a product, we need to listen for that event -2. When that event happens we need to **filter the products** the user wants -3. Then we should **render those products** - -Lets get a little closer to javacript: -1. `.addEventListener` on an element -2. `.filter` on the products array -3. `renderProducts` with the filtered array - -#### Searching for products -When the user writes something in the search input field. The products should be updated to only include the products that match the name. Use the overview shown above and the `renderProducts` function. - -#### Showing products that ships to country - *optional* -Lets help a user to avoid spending too much time looking for products that can not be shipped to the user's country: When the **user selects a country** in the ships to select tag, the products should be updated with the **products that ship to that country**. - -Hint 1: Break this task into smaller tasks! - -Hint 2: How can you get a value from a select list? Its a little tricky, but google and slack is your friend! - -Hint 3: To figure out if a product does ship to a country, use [includes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) - -### Create some extra feature -No matter how small or how big. Create some feature that would be **cool/helpful/quirky/funny**. - -### Sort the products - *optional* -Choosing one of the sorting metods should update the shown order of the products. There is an array method called `sort`. Find documentation about it and see if you can get it to work. Use the `renderProducts` function. - -### Shopping cart - *optional* -When clicking the `Add to cart` button for a product, that product should be added to the `ul` found under the section with the classname `cart`. The product should be added as a an `li` item. Like this: - -```html -
      • -
        Drone
        -
        1234
        -
      • -``` -Hint 1: Getting the object of the clicked product can be tricky! Here is one way: -1. When adding the li tags to the ul. You can for every product in the products array create a new li element using `document.createElement('li')`. You then set the innerHTML as is specified above and then attach a clickListner: `createdLiElement.addEventListener('click', () => {});` The callback function has access to the product object because of something called [closures](https://www.youtube.com/watch?v=1JsJx1x35c0). This approach i would say is the best way. - -![Shopping cart](https://media.giphy.com/media/8PA8Ew3nw97yg/giphy.gif) - -## Feedback giving time! -Find a student to give feedback using this site: https://hyf-peer-review.herokuapp.com/ -The feedback should be given after the homework has been handed in preferably latest two days after. - -To help you get started we have created some ressources about giving feedback. Find them here: https://github.com/HackYourFuture-CPH/curriculum/tree/master/review - -## Hand in Homework: -Go over your homework one last time: - -- Does every file run without errors and with the correct results? -- Have you used `const` and `let` and avoided `var`? -- Do the variable, function and argument names you created follow the [Naming Conventions](https://github.com/HackYourFuture/fundamentals/blob/master/fundamentals/naming_conventions.md)? -- Is your code well-formatted (see [Code Formatting](https://github.com/HackYourFuture/fundamentals/blob/master/fundamentals/naming_conventions.md))? - -![check](https://media.giphy.com/media/l4EpblDY4msVtKAOk/giphy.gif) - -If you can answer yes to the above questions then you are ready to hand if the homework: - -- Use the `hyf-homework` repo and add your homework files in the `javascript/javascript2/week2` folder -- Make your commits for the homework. Remember to seperate the code into meaningful commits! -- Push the changes to github -- To finish the homework post the link for your repo and the rendered index.html on your classes slack channel - ---- - -🎉 - diff --git a/javascript2/week2/homework/hyf-bay/hyfBayHelpers.js b/javascript2/week2/homework/hyf-bay/hyfBayHelpers.js deleted file mode 100644 index c80de6d2..00000000 --- a/javascript2/week2/homework/hyf-bay/hyfBayHelpers.js +++ /dev/null @@ -1,68 +0,0 @@ -/* DONT MODIFY ANY OF THIS CODE!!!*/ - -window.getAvailableProducts = function() { - function getRandomInt(min, max) { - min = Math.ceil(min); - max = Math.floor(max); - return Math.floor(Math.random() * (max - min + 1)) + min; - } - - function getRandomItem(availableProductNames) { - return availableProductNames[getRandomInt(0, availableProductNames.length - 1)]; - } - - function getRandomProductname() { - const preWords = ['Used', 'Fantastic', '"Used"', 'Broken', 'Beautiful', 'Wet', 'Green', 'Sloppy', 'Dirty']; - const productNames = ['Carrot', 'Drone', 'Giftcard', 'Puppy', 'Car', 'Shirt', 'Milk', 'Chalk', 'Fish fingers', 'Socks', 'Chocolate', 'Toothbrush', 'Computer', 'Nokia', 'Cologne']; - - let chosenProductName = getRandomItem(productNames); - const shouldHavePreWord = getRandomInt(0, 10) > 6; - - if (shouldHavePreWord) { - const preWord = preWords[getRandomInt(0, preWords.length - 1)]; - chosenProductName = `${preWord} ${chosenProductName}`; - } - - return chosenProductName; - } - - /* DONT MODIFY ANY OF THIS CODE!!!*/ - function getRandomCountries() { - const availableCountries = ['Denmark', 'Sweden', 'Norway', 'Germany', 'Iceland', 'England']; - const numberOfCountries = getRandomInt(1, 3); - - const randomCountries = []; - while (randomCountries.length < numberOfCountries) { - const randomIndex = getRandomInt(0, availableCountries.length - 1); - const randomCountry = availableCountries[randomIndex]; - if(!randomCountries.includes(randomCountry)) { - randomCountries.push(randomCountry); - } - } - - return randomCountries; - } - - const numberOfAvailableProducts = getRandomInt(0, 30); - const availableProducts = Array.apply(null, Array(numberOfAvailableProducts)) - .map(() => { - const name = getRandomProductname(); - return { - id: `${name}${getRandomInt(0, 100000)}`, - name, - price: getRandomInt(0, 10000), - rating: getRandomInt(1, 10), - shipsTo: getRandomCountries(), - }; - }); - - return availableProducts; -} - -window.sendPricesToServer = function(prices, callback) { - console.log(`Sending these prices: ${prices} to an analytics server`); - - setTimeout(() => { - callback(`These prices were received ${prices}`); - }, 3000) -} \ No newline at end of file diff --git a/javascript2/week2/homework/hyf-bay/main.css b/javascript2/week2/homework/hyf-bay/main.css deleted file mode 100644 index ba2889b6..00000000 --- a/javascript2/week2/homework/hyf-bay/main.css +++ /dev/null @@ -1,121 +0,0 @@ -body { - font-family: "Open Sans", sans-serif; - background-color: #F9FBFD; -} - -* { - box-sizing: border-box; -} - -body, h1, h2 { - margin: 0; -} - -ul { - list-style-type: none; - margin: 0; - padding: 0; -} - -header { - background-color: white; - box-shadow: 0 1px 2px rgba(190, 190, 190, 0.5); -} - -header .wrapper { - width: 800px; - margin: 0 auto; - height: 80px; - background: #FFFFFF; - position: relative; -} - -header .wrapper h1, header .wrapper h2 { - position: absolute; - top: 50%; - transform: translateY(-50%); -} - -header .wrapper h2 { - left: 125px; -} - -/*#FF813F*/ - -section.table-view-control, section.products, section.cart { - max-width: 800px; - margin: 0 auto; -} - -section.table-view-control, section.products { - margin: 24px auto 12px; - background-color: white; - box-shadow: 0 1px 2px rgba(190, 190, 190, 0.5); - border-radius: 8px; -} - -section.table-view-control { - padding: 12px; -} - -section.table-view-control>div, section.table-view-control .filters>div { - margin-bottom: 24px; -} - -section.products>ul { - padding: 0; -} - -section.products>ul>li>ul { - display: flex; - justify-content: space-between; - align-items: center; - padding: 12px 12px 12px 12px; -} - -section.products>ul>li>ul>li:first-child { - width: 200px; -} - -section.products>ul>li:nth-child(odd) { - background-color: #f0f0f0; -} - -section.products li div, section.products li button { - margin-right: 12px; - width: 100px; -} - - -section.products li .name { - width: 200px; -} - -section.cart { - position: fixed; - bottom: 12px; - right: 12px; - width: 300px; - height: 200px; - background-color: white; - overflow-y: auto; - box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2); - padding: 12px; - border-radius: 8px; -} - -section.cart ul { - list-style-type: none; - margin: 0; - padding: 0; -} - -section.cart ul>li { - display: flex; - justify-content: space-between; - padding: 6px; -} - -section.cart ul>li:nth-child(odd) { - background-color: #f0f0f0; -} \ No newline at end of file diff --git a/javascript2/week2/lesson-plan.md b/javascript2/week2/lesson-plan.md index 51ce8f53..0c6235a8 100644 --- a/javascript2/week2/lesson-plan.md +++ b/javascript2/week2/lesson-plan.md @@ -1,19 +1,26 @@ # Lesson plan + +## Lesson materials +These are some examples of previously created materials by mentors that you can use yourself, or for inspiration. +- [Notion Page Handout](https://dandy-birth-1b2.notion.site/HYF-Aarhus-JS-2-Week-2-cd0c1163d0264215824dc17580c97825?pvs=4) (by [Thomas](https://github.com/te-online)) + +--- + ``` > Focus on having lots of in class exercises. -> DONT teach everything, let the students investigate topics on their own aswell! +> DON'T teach everything, let the students investigate topics on their own as well! -> Focus on how to read documentation, google answers and google errors!! +> Focus on how to read documentation, Google answers and errors!! > Teach towards the students being able to solve the homework ``` -Remember to add the code you wrote in the class to the relevant class branch's class work folder. If the branch has not been created just create and push it :) If you dont have access, write to one from the core team. You can see an example below! +Remember to add the code you wrote in the class to the relevant class's work folder on a branch. If the branch has not been created just create and push it :) If you don't have access, write to someone from the core team. You can see an example below! -To find examples of what teachers have taught before go to the class branches in the classwork folder, Fx [class 07](https://github.com/HackYourFuture-CPH/JavaScript/tree/class07/JavaScript1/Week1/classwork) +To find examples of what teachers have taught before, go to the class branches in the classwork folder, Fx [class 07](https://github.com/HackYourFuture-CPH/JavaScript/tree/class07/JavaScript1/Week1/classwork) -If you find anything that could be improved then please create a pull request! We welcome changes, so please get involved if you have any ideas!!! +If you find anything that could be improved, please create a pull request! We welcome changes, so please get involved if you have any ideas!!! --- @@ -44,6 +51,11 @@ If you find anything that could be improved then please create a pull request! W [Listing project](#listing-project) + +## Flipped classroom videos + +[Flipped classroom videos](https://github.com/HackYourFuture-CPH/JavaScript/blob/main/javascript2/week2/preparation.md#flipped-classroom-videos) + ## Code inspiration ### Mentors @@ -291,6 +303,7 @@ function generateListings(numberOfListings) { listing.price = randomIntFromInterval(1, 10000); listing.hasGarden = Boolean(randomIntFromInterval(0, 1)); listing.size = randomIntFromInterval(12, 1000); + listing.img = `https://loremflickr.com/200/200/${listing.type}` listings.push(listing); } @@ -310,7 +323,7 @@ generateListings(20); ### Filter Using the 37 listings from the previous tasks - Create an array of cheap listings. You define what cheap means. Each item in this array should be of type object -- Create an array of expensize listings prices. Each item in this array should be of type number +- Create an array of expensive listings prices. Each item in this array should be of type number - Create an array of listings that have parking. Each item in this array should be of type object diff --git a/javascript2/week2/optional-homework.md b/javascript2/week2/optional-homework.md new file mode 100644 index 00000000..178c4024 --- /dev/null +++ b/javascript2/week2/optional-homework.md @@ -0,0 +1,138 @@ +> [!WARNING] +> These are optional homework exercises that you can complete on top of your [homework project](/homework-projects/readme.md), if you wish. There is no requirement for these to be reviewed, but feel free to ask a mentor if you wish for some feedback. + +# Optional Homework + +## Why should i even do this homework? + +Working with arrays is an essential part of being a javascript developer. A lot of the time js developers have an array of some objects. That could be **users, products, posts, jobs** etc. Working with these arrays, js developers so often need to filter the arrays, change the structure of the array, sort them or loop through them. + +On top of that combining these array function with each other will show the functional side to javascript in a nice way. + +The warmup exercises will be a bit abstract. But the in the **hyfBay exercise** the task will be a lot closer to a **real world task**. + +## Appreciate how far you have come + +Javascript is getting difficult now and we are aware of that! Take some time to appreciate how far you have come that last 6 weeks. Instead of comparing yourself to others, compare yourself to where you were a some time ago. If you are seeing progress then you are doing it right 💪 + +## Overview of homework + +1. **[Warmup array exercises:](#1-warmup-array-exercises)** Warmup exercise that includes + + - Doubling the number + - ⭐ Working with movies + +2. 🌟 **[hyfBay](#hyfbay):** It's a single-page app where users can search for products. + +# 1. Warmup array exercises + +If you struggle to do this weeks homework there are a couple of things to do: + +- Try watch this video: https://www.youtube.com/watch?v=Urwzk6ILvPQ +- Watch the class recording. If it for some reason is missing. Then watch these: [part 1](https://www.youtube.com/watch?v=AJt_O0EFDC8), [part 2](https://www.youtube.com/watch?v=4tj7CvD7ka8), [part 3](https://www.youtube.com/watch?v=CO40FG6pK2k) [part 4](https://www.youtube.com/watch?v=eA2tCs0AaaM) +- Read up on array functions [here](https://github.com/HackYourFuture-CPH/JavaScript/blob/main/javascript2/week2/readme.md#array-methods-map-filter-and-sort) + +## 1.1. Doubling of number + +Say you would like to write a program that **doubles the odd numbers** in an array and **throws away the even number**. + +Your solution could be something like this: + +```js +let numbers = [1, 2, 3, 4]; +let newNumbers = []; + +for (let i = 0; i < numbers.length; i++) { + if (numbers[i] % 2 !== 0) { + newNumbers[i] = numbers[i] * 2; + } +} + +console.log("The doubled numbers are", newNumbers); // [2, 6] +``` + +Rewrite the above program using `map` and `filter` don't forget to use arrow functions. + +
        + +## 1.2. codewars! + +Complete these Katas: +- [8 kyu To square(root) or not to square(root)](https://www.codewars.com/kata/57f6ad55cca6e045d2000627) +- [8 kyu Removing Elements](https://www.codewars.com/kata/5769b3802ae6f8e4890009d2) + +
        + +## 1.3. Working with movies + +![cinema](https://media.giphy.com/media/l6mBchxYZc7Sw/giphy.gif) + +Copy the movies array in the [movies](homework/movies.js) file. Use this array to do the following tasks: + +1. Create an array of movies containing the **movies with a short title** (you define what short means) +2. Create an array of movie titles with **long movie titles** +3. Count the **number of movies** made between 1980-1989 (including both the years) +4. Create a new array that has an **extra key called tag**. The tag is based on the rating: Good (>= 7), Average (>= 4 and < 7), Bad (< 4) +5. **Using [chaining](readme.md#chaining)**, first filter the movies array to only contain the movies rated higher than 6. Now map the movies array to only the rating of the movies. +6. **Count the total number of movies** containing any of following keywords: `Surfer`, `Alien` or `Benjamin`. So if there were 3 movies that contained `Surfer`, 1 with `Alien` and 2 with `Benjamin`, you would return 6. Can you make sure the search is case insensitive? +7. Create an array of movies where a **word in the title is duplicated**. Fx "Star **Wars**: The Clone **Wars**" the word **Wars** is duplicated. Here are some madeup examples of movies with duplicated words in the title: "**The** three men and **the** pistol", "**Chase** three - The final **chase**" +8. Calculate the **average rating** of all the movies using [reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce). _Optional_ +9. **Count the total number** of Good, Average and Bad movies using [reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce). A return could fx be `{goodMovies: 33, averageMovies: 45, goodMovies: 123}` _Optional_ + +# 2. hyfBay - get the okay'est products here - continued + +**Continue work on your homework regarding the Hyfbay** from previous week. Please copy the files from last week into this weeks `hyf-homework` folder and continue working there. If you have not made last weeks homework the solution for it is included in [this weeks homework folder](homework/hyf-bay) in the `main.js` file. + +## 2.1. Filter products + +A very normal usecase for a product site is that a **user wants to search for some product** or find products that are cheaper than a set price. Lets implement that functionality for a user! + +BUT first lets figure out what happens on a conceptual level, when a user filters some products: + +1. Some kind of **event happens**, fx a user searches for a product, we need to listen for that event +2. When that event happens we need to **filter the products** the user wants +3. Then we should **render those products** + +Lets get a little closer to javacript: + +1. `.addEventListener` on an element +2. `.filter` on the products array +3. `renderProducts` with the filtered array + +## 2.2 Searching for products + +A user needs to search for products. That means that we need to add an input element to the html. + +When the user writes something in the search input field. The products should be updated to only include the products that match the name. + +So what event should we listen for in the `addEventListener` method? And what element should we listen on? + +Use the overview shown above and the `renderProducts` function. + +![Searching for a product](homework/hyf-bay-searching.gif) + +## 2.3. Filter products based on max price + +Lets help a user to find cheap products! When the **user writes a maximum price** the products should be filtered to match that maximum price + +_Hint: Break this task into smaller tasks!_ + +![Searching for a product](homework/hyf-bay-price.gif) + +## 2.4. Make the website look nicer! + +The website looks awful now, **but** luckily you have had css and html and know exactly what it takes to make this website shine! + +Improve it how you see fit. Maybe add a footer, header, logo, title, styling, responsivity. Whatever you feel like would improve the site! + +## 2.5. Create some extra feature + +No matter how small or how big. Create some feature that would be **cool/helpful/quirky/funny**. + +## 2.6 Sort the products - _optional_ + +This task is more open ended! So you need to come up with fx how the user should interact with the functionality. + +Give the user the possibility to sort the products. That could fx be on price, name, rating or all of the above! + +
        \ No newline at end of file diff --git a/javascript2/week2/optional-homework/hyf-bay-price.gif b/javascript2/week2/optional-homework/hyf-bay-price.gif new file mode 100644 index 00000000..177f5299 Binary files /dev/null and b/javascript2/week2/optional-homework/hyf-bay-price.gif differ diff --git a/javascript2/week2/optional-homework/hyf-bay-searching.gif b/javascript2/week2/optional-homework/hyf-bay-searching.gif new file mode 100644 index 00000000..03bb772f Binary files /dev/null and b/javascript2/week2/optional-homework/hyf-bay-searching.gif differ diff --git a/javascript2/week2/optional-homework/hyf-bay/hyfBayHelpers.js b/javascript2/week2/optional-homework/hyf-bay/hyfBayHelpers.js new file mode 100644 index 00000000..e52b3b25 --- /dev/null +++ b/javascript2/week2/optional-homework/hyf-bay/hyfBayHelpers.js @@ -0,0 +1,99 @@ +/* DONT MODIFY ANY OF THIS CODE!!!*/ + +window.availableCountries = [ + "Denmark", + "Sweden", + "Norway", + "Germany", + "Iceland", + "England", +]; + +window.getAvailableProducts = function () { + function getRandomInt(min, max) { + min = Math.ceil(min); + max = Math.floor(max); + return Math.floor(Math.random() * (max - min + 1)) + min; + } + + function getRandomItem(availableProductNames) { + return availableProductNames[ + getRandomInt(0, availableProductNames.length - 1) + ]; + } + + function getRandomProductname() { + const preWords = [ + "Used", + "Fantastic", + '"Used"', + "Broken", + "Beautiful", + "Wet", + "Green", + "Sloppy", + "Dirty", + ]; + const productNames = [ + "Carrot", + "Drone", + "Giftcard", + "Puppy", + "Car", + "Shirt", + "Milk", + "Chalk", + "Fish fingers", + "Socks", + "Chocolate", + "Toothbrush", + "Computer", + "Nokia", + "Cologne", + ]; + + let chosenProductName = getRandomItem(productNames); + const shouldHavePreWord = getRandomInt(0, 10) > 6; + + if (shouldHavePreWord) { + const preWord = preWords[getRandomInt(0, preWords.length - 1)]; + chosenProductName = `${preWord} ${chosenProductName}`; + } + + return chosenProductName; + } + + /* DONT MODIFY ANY OF THIS CODE!!!*/ + function getRandomCountries() { + + const numberOfCountries = getRandomInt(1, 3); + + const randomCountries = []; + while (randomCountries.length < numberOfCountries) { + const randomIndex = getRandomInt(0, window.availableCountries.length - 1); + const randomCountry = window.availableCountries[randomIndex]; + if (!randomCountries.includes(randomCountry)) { + randomCountries.push(randomCountry); + } + } + + return randomCountries; + } + + const numberOfAvailableProducts = getRandomInt(0, 30); + const availableProducts = Array.apply( + null, + Array(numberOfAvailableProducts) + ).map(() => { + const name = getRandomProductname(); + return { + id: `${name}${getRandomInt(0, 100000)}`, + name, + price: getRandomInt(0, 10000), + rating: getRandomInt(1, 10), + shipsTo: getRandomCountries(), + }; + }); + + return availableProducts; +}; diff --git a/javascript2/week2/homework/hyf-bay/index.html b/javascript2/week2/optional-homework/hyf-bay/index.html similarity index 100% rename from javascript2/week2/homework/hyf-bay/index.html rename to javascript2/week2/optional-homework/hyf-bay/index.html diff --git a/javascript2/week1/homework/hyf-bay/main.css b/javascript2/week2/optional-homework/hyf-bay/main.css similarity index 100% rename from javascript2/week1/homework/hyf-bay/main.css rename to javascript2/week2/optional-homework/hyf-bay/main.css diff --git a/javascript2/week2/homework/hyf-bay/main.js b/javascript2/week2/optional-homework/hyf-bay/main.js similarity index 84% rename from javascript2/week2/homework/hyf-bay/main.js rename to javascript2/week2/optional-homework/hyf-bay/main.js index 7ff843ce..d148828a 100644 --- a/javascript2/week2/homework/hyf-bay/main.js +++ b/javascript2/week2/optional-homework/hyf-bay/main.js @@ -8,7 +8,8 @@ function renderProducts(products) { products.forEach(product => { const li = document.createElement('li'); - const shipsToHTML = product.shipsTo.reduce((acc, country) => `
      • ${acc}
      • ${country}
      • `); + let shipsToHTML = ''; + product.shipsTo.forEach(country => shipsToHTML += `
      • ${country}
      • `); li.innerHTML = `