js-school's People
js-school's Issues
Recipe Search - Part 1 - Create initial markup and styling
Acceptance Criteria
Create the markup and styling to the Recipe Finder app.
DEV Instructions
- Create the initial HTML structure
- This includes the form and the cards. It's good practice to build out everything first, then break it apart once we start using JS.
- Style the HTML using CSS. Feel free to use a CSS library. Here are some examples
- For the font icons, you can use Font Awesome
Extra credit
Feel free to continue to Part 2 once you get Part 1 done.
Design
Recipe Search - Part 6 - Add additional filter to form
Overview
Adds an additional filter to our form.
Acceptance Criteria
A user should have the option to also filter by diet type
Dev instructions
- Create a select list of diet types
- Figure out the parameter you need to target from the Search Recipes docs
- Add the value from the selected option to the parameter found in step 2.
Example
Class 16
Items covered in todays class
- Implemented the
open
andclose
methods. - Jeremy realized we needed a method to initialize our click event handler(s), so we created a
initializeEvents
method - Used
classList
to add, remove and toggle classes - Used
style
property to add inline styles to our modal element - Introduced the
addEventListener
method to handle ourclick
event - How to use
getElementsByClassName
- How to use
querySelector
QUIZ
- What is a constructor function in JS?
- What does the
new
keyword do? - What is this
prototype
property? - Are there any benefits to using constructor functions?
- What does "instance" mean in JS?
Homework if you so dare to try!!
https://github.com/jeremypeter/js-school/tree/master/class-16
Go ahead and add to the modal.html
file the following:
- Create a new
<button>
element - Add a class of
close
to the button - Add
Close
as the text for the button - Add/append the close button to the modal container
- Inside of the
initializeEvents
method, add anotherclick
event listener to the close button- When the close button is clicked, it should hide the modal
Homework 7
Last week we talked about truthy and falsy values and worked on getting the basics of logical operators down. Let's follow our discussion up with a nice little quiz!
Quiz on logical operators
Given the following variables:
var a = 10;
var b = 0;
var c = 'jeremy';
var d;
var e = '23';
var f = 4564;
var g = '10';
What boolean value will be returned:
a > f
b
e || d
g == a
g !== b && c
c.length <= f
b || d || (b > a) || e
a === g
c.length
d === undefined
Create a join
function
Using a for
loop, create a join
function that takes two arrays as parameters and returns a new array that combines the two.
var a = [1,2,3,4];
var b = [5,6,7,8,9,10];
function join(arr1, arr2){
// add functionality
}
console.log(join(a, b)) // [1,2,3,4,5,6,7,8,9,10]
while
loop
Using the expression below, create a while
loops that counts the number of times it takes to loop before landing on number 50
. Then log the final count
.
0 to 100 expression: Math.round(Math.random() * 100)
var count = 0;
// write while loop
console.log('It took ' + count + ' loops to get to land on 50.');
Recipe Search - Part 2 - Create custom library with some helper methods
Now that we've statically built out the Recipe Search using just HTML and CSS, we can now move on to some JS .
In Part 2, we'll be building our own custom JS library that will contain methods to handle requests made to the Spoonacular API and have a couple of additional helper methods.
Library Description
We'll be calling our library Requecipe
(Request + Recipe) hahahahaha :-).
Example usage
const requecipe = new Requecipe();
const parameters = { query: 'pizza', count: 12 }
const query = requecipe.createQueryString(parameters);
console.log(query) // => 'query=pizza&count=12'
const formattedTime = requecipe.formatServingTime(89)
console.log(formattedTime) // => '1h 29min'
Acceptance Criteria
1. Create js file and constructor function
- Create a file called
requecipe.js
to store our library and it's logic, then load the script in your HTML file - Within
requecipe.js
create a constructor function calledRequecipe
2. Create createQueryString
prototype method
The purpose of this method is to convert an object literal { key: 'value' }
into a query string key=value
.
Instructions
- Create a prototype method on the
Requecipe
constructor calledcreateQueryString
- The
createQueryString
method should:- Take in an object literal as a parameter
- Convert the object literal into a query string format e.g.
key1=value&key2=value
return
the converted string
3. Create formatServingTime
prototype method
The purpose of this method is to take a number in minutes and convert it to HH mm
format.
e.g. 125
-> 1h 5min
- Create a prototype method on the
Requecipe
constructor calledformatServingTime
- The
formatServingTime
method should:- Take in an number as a parameter
- Convert the number into a string in the format of hour and/or minutes. So if a user passes
125
as the parameter, it'll calculate the hour and/or minutes which is1h 5min
. HINT for figuring out minutes, find which JS arithmetic operator you'll use to get the remainder. return
the formatted string
Homework 10
Scope/Hoisting Quizzes
We've talked briefly about global
, local
, and lexical
scope. Other types of scope terminology you may hear about are block
, function
, nested
scope. Those just fall under the same category of local
scope.
- Global scope
- Local scope
- Block scope
- Function scope
- Nested scope
Quiz 1
var name = 'Germz';
function roundNumber(number){
var num = Math.round(number);
return num;
}
- What scope is the
name
variable in? - What scope is the
num
variable in? - What scope is the
roundNumber
function in?
Quiz 2
var name = 'Germz';
function getName(){
return lowercase(name);
function lowercase(str){
return str.toLowerCase();
}
}
console.log(name);
- What scope is the
getName
function in? - What scope is the
lowercase
function in? - What will the
console.log(name)
return? - What is it called when we're able to leverage a variable that is outside of the current scope we're in?
Quiz 3
Why does the following code throw an error?
var name = 'Jeremy';
function name(){
return 'Bill';
}
console.log(name());
Quiz 4
var animal = 'Cat';
{
let animal = 'Dog';
}
console.log(animal);
- What scopes are being used in the above code (choose all that apply)?
- Global
- Local
- Function
- Block
- Nested
- Why does't
console.log(animal)
returnDog
?
Homework 1
The following assignment contains some badData
that we just received from a server of some sort. We now need to clean up the data. I've started the code for you with some expected results from the cleanBadData
function.
- Copy the code to an html file so you can debug using Chrome console
- There's a
cleanupBadData
function declaration I created that you'll need to fill in - There's going to be at least 2 other "pure function" you'll need to create to trim and lowercase the array of string data.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
// We just recieved an array of data from a server somewhere
// that needs to be cleaned up by removing the extra spaces
// in the beginning and ending of the strings and we should
// also make the strings all lowercase to keep them consistent
var badData = [
' mElaNie',
'chINmaYi ',
' MilijanA ',
' amAnDa'
];
// Execute the `cleanupBadData` function
var newData = cleanupBadData(badData);
// Log results of `newData`
// Should returned ['melanie', 'chinmayi', 'milijana', 'amanda']
console.log(newData);
/*************************************************************
* FUNCTION DECLARATIONS
* Add your function declarations below
*************************************************************/
function cleanupBadData(data) {
// 1. Create a new array so we can push newly formatted data to
// 2. Loop through `data` array. Inside the loop you should:
// - 2.1 Create pure function to trim the string of spaces at the beginning and end (see `trimgString` function below)
// - 2.2 Create pure function convert all string characters to lowercase (see `lowercaseString` function below)
// - 2.3 Push newly formed string into the new array created in step 1
// 3. Return the new array you created
}
function trimString(str) {
// Add logic
}
function lowercaseString(str) {
// Add logic
}
</script>
</head>
</html>
Have questions?
Leave a comment in the issue so we can discuss and drop hints to one another.
Recipe Search - Part 3 - Enhance custom library and make a call to API
Let's continue with extending our Requecipe
library we created from Part 2. Today we'll be interacting with the Spoonacular API by making GET
requests using the browser's Fetch API.
Example usage
Below is a method we'll create to get data from the Search Recipes endpoint. Notice the property names of the object assigned to the parameters
constant match the parameter names of the Search Recipes endpoint.
const requecipe = new Requecipe();
const apiKey = 'YOUR_API_KEY'
const parameters = { query: 'pizza', number: 12, apiKey: apiKey }
requecipe.searchRecipes(parameters)
.then(function(data){
// => {...} data from Search Recipes endpoint
console.log(data)
});
Acceptance Criteria
1. Create searchRecipes
prototype method
The purpose of this method is to return
the JSON response data from the Search Recipes endpoint.
- Create a prototype method on the
Requecipe
constructor calledsearchRecipes
- The
searchRecipes
method should:- Take in an object literal as the function parameter
- Build the URL needed to make a request to the Search Recipes api (see their example GET request).
- Use the Fetch API to make a request to the Search Recipes api
return
the Promise fulfilled with the JSON data (more on promises)
Recipe Search - Part 5 - Render results to page using markup created in Part 1
Great work so far!! We're now able to retrieve results based on user submissions. Up until this point, we've just been logging results. Now it's time to render HTML based on the results we get back!!
In Part 1, we created the markup and styling to make it look super sweeeeeet. We now need to build the markup for each card using JS and add it to the container that houses the cards. This is pretty easy to do using template literals and a DOM Element's innerHTML property. Here's a good article on how to use them https://wesbos.com/template-strings-html/
Dev instructions
- Loop over the results building up a string of cards
- Use information from each result to dynamically set the image, title, time it takes to cook, and the serving size
- Add that string of cards to the card container
Homework 11
We learned about:
let
andconst
- Don't get hoisted.
- Stay within their current scope.
- Some developers/tutorials may say to use
let
overvar
var
- Get's hoisted when inside of a block scope that isn't
function
scope.
- Get's hoisted when inside of a block scope that isn't
- The difference between function declarations and function expressions.
- When would someone use a function declaration over a function expression.
Quiz
- Which of the following is a function expression and a function declaration?
A)B)function test1(){}
var test1 = function(){}
- Why would you use a function expression over a function declaration?
- Given the following code, why does
console.log(firstCode)
log"charlie"
when thefirstCode
variable is contained in a block scope?var codes = ['charlie', 'fox', 'alpha']; if(codes.length > 1) { var firstCode = codes[0]; } console.log(firstCode);
- Given the following code, why does
console.log(firstCode)
NOT log"charlie"
?var codes = ['charlie', 'fox', 'alpha']; if(codes.length > 1) { let firstCode = codes[0]; } console.log(firstCode);
- Given the following code, why does
console.log(data)
throw an error?const data = []; data = {}; console.log(data);
- Given the following code, what gets outputted and why?
const animals = []; const names = {}; animals.push('cat'); names.ben = true console.log(animals); console.log(names)
Homework 4
Objects
var ageVar = 'age';
var data = {};
Given the data
object above:
- What are at least 2 other ways to create a new
data
object? - How can we "set" a property of
name
on thedata
object to have valuetimmy
? Give at least 2 ways to set an object. - How can we "get" the value of the
name
property on thedata
object? Give at least 2 ways to get a value from an object property. - How can we "set" the value of
ageVar
as a property on thedata
object with a value of 10 e.g.{ age: 10 }
- How do we set duplicate properties on an object? e.g.
{ age: 10, age: 25, age 15 }
- What data types can you have as values to properties on an object?
Extra Credit
Your tasks is to take an array of emails whose final output should be an object that groups the emails whose properties consist of the domains of the emails and the value is an array of emails related to that domain.
var emails = [
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]'
];
function groupEmails() {
// Add Logic
}
var group = groupEmails(emails);
console.log(group);
// {
// meltmedia: [
// '[email protected]',
// '[email protected]',
// '[email protected]',
// ],
// apple: [
// '[email protected]'
// ],
// gene: [
// '[email protected]',
// '[email protected]'
// ]
// }
Homework 5
Challenge 1
We've received an array that has a plethora of data types we don't need. Ewwwww! All we care about are the numbers in the array. So our task is to filter out the numbers from the array.
- Loop over the
clutter
array - Within the loop, create an
if
conditional that uses the typeof keyword to check if the current item being is anumber
- If it's a
number
push it to the newnumbers
array - If it's not a
number
do nothing
function getNumberThree(){
return 3;
}
var clutter = [
'hello',
getNumberThree(),
undefined,
{},
12,
false,
34,
null,
'yo',
45,
function getStuff(){},
'',
0,
getNumberThree
];
var numbers = [];
// Add logic here!
console.log(numbers); // returns [3, 12, 34, 45];
Recipe Search - Part 7 - Add "Load More" button
Homework 3
Do this
var firstNames = [
' chinMayi ',
'meLanie ',
'aManda ',
'milijAna '
];
var lastNames = [
'chauHan ',
' schmiTZ',
'Rineer',
'arsEniJevic'
];
/**
*
* Takes an array of first names and last names and creates
* a new array of objects that has values cleaned and
* in object form
*
* @param {array} firstNames - array of first names
* @param {array} lastNames - array of last names
*
* @return new array of objects
*
* @example
* console.log(createNameObject(firstNames, lastNames));
*
* returns the following:
* [
* {
* firstName: 'chinmayi',
* lastName: 'chauhan'
* },
* {
* firstName: 'melanie',
* lastName: 'schmitz'
* },
* {
* firstName: 'amanda',
* lastName: 'rineer',
* },
* {
* firstName: 'milijana',
* lastName: 'arsenijevic'
* }
* ]
*/
createNameObject(firstNames, lastNames){
// Add Logic
}
// Execute `createNameObject`
var cleanedNames = createNameObject(firstNames, lastNames);
console.log(cleanedNames);
Class 17
Homework Fun Stuff
- Extend the modal functionality by adding the ability to close the modal when a user hits the escape key. Search the Event API to see if there are any keyboard events you can leverage.
- Style the modal to look all pretty-n-stuff!
Recipe Search - Part 4 - Log api results based on user submission
In Part 3, we hardcoded the value of the query
parameter to be pizza
. Now that we can retrieve data from the Spoonacular API with our custom Requecipe
library, let's dynamically search for recipes when the user submits the form. NOTE: we don't have to render the results yet, we're just console.log
ing them for now.
Dev Instructions
- Create a
scripts.js
file and link that to yourindex.html
file - Add the logic to handle user submissions to the
scripts.js
file
Acceptance Criteria
Homework 9
The following exercise uses the browser's fetch API to pull data from a couple of API endpoints that get posts and comments.
You can ignore the code between the IGNORED CODE
comment blocks for now. We'll look at that in the future.
Acceptance Criteria
Create a new data structure that contains the emails of all of the commenters of a particular post. See the JSDoc block above the getCommenterEmails
function for details.
<!DOCTYPE html>
<html lang="en">
<body>
<script>
/*****************************************************************
* BEGIN IGNORED CODE
****************************************************************/
// Uses browsers `fetch` api to get data
const getPosts = fetch('https://jsonplaceholder.typicode.com/posts')
.then(res => res.json());
// Uses browsers `fetch` api to get data
const getComments = fetch('https://jsonplaceholder.typicode.com/comments')
.then(res => res.json());
// Get data and pass it to `getCommenterEmails` function,
// then console log the data that `getCommenterEmails` returns;
Promise.all([getPosts, getComments])
.then(data => {
let posts = data[0];
let comments = data[1];
return getCommenterEmails(posts, comments);
})
.then(console.log);
/*****************************************************************
* END IGNORED CODE
****************************************************************/
/**
* Creates a new array of data that adds gathers all of the emails
* from comments of a particular post.
*
* @param {Array} posts
* Array of posts from API
* @param {Array} comments
* Array of comments from API
* @returns {Array}
* Array of data that contains the `postTitle`, `postId` and `emails`
*
* @example
* [
* {
* postTitle: 'Post 1',
* postId: 1,
* emails: [
* '[email protected]',
* '[email protected]'
* ]
* }
* ]
*/
function getCommenterEmails(posts, comments){
let cleanedData = [];
// Add functionality
return cleanedData;
}
</script>
</body>
</html>
Homework 8
ExerSize 1
- Create our own
pop
andpush
functions to mimic the functionality of the nativeArray.pop()
andArray.push()
methods. - Use a
switch
statement to return the price for items passed in to thegetMenuPrice()
function
var food = [
'steak',
'pizza',
'celery'
];
var newPopArr = pop(food);
console.log(newPopArr);
// => ['steak', 'pizza']
push('gum', food);
console.log(food);
// => ['steak', 'pizza', 'celery', 'gum']
console.log(getMenuPrice('steak'));
// The price for steak is $5.00.
console.log(getMenuPrice('burger'));
// Could not find burger on the menu.
/***********************************************************
* Function declartions below
***********************************************************/
/**
* Removes the last item in an array and returns a new array
* with the last item removed.
*
* @param {Array} arr The array to query
* @return {Array} New array with last item removed
*/
function pop(arr){
// Add functionality.
}
/**
* Takes an `item` and adds it to end of the `arr`
*
* @param {String} item Datatype to be added to array.
* @param {Array} arr Array to add `item` to.
* @returns {Array} Altered `arr`.
*/
function push(item, arr){
// Add functionality.
}
/**
* Get's the price of food item if found in the menu object, otherwise
* it returns a string that says: "Could not find `foodItem` on the menu."
*
* @param {String} foodItem Items to
* @returns {String} String based on price, otherwise a default statement.
*/
function getMenuPrice(foodItem){
var cost = 0;
var menu = {
steak: 5.00,
apples: 6.23,
salt: 34.23
};
// Finish functionality using a `switch` statement
}
Homework 12
Ooooo we're getting into some fun topics now! Today we discussed:
- Asynchronous vs synchronous in JS
- Different ways to handle asynchronous functions:
- Callbacks
- Promises (my second favorite)
- Async/Await (my favorite)
- Generators
- What is callback hell: http://callbackhell.com
- How
setTimeout
works - Event loop and event queue (https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop)
- A talk that helped me understand the event loop: https://www.youtube.com/watch?v=8aGhZQkoFbQ
Front end masters course: https://frontendmasters.com/courses/javascript-new-hard-parts/introducing-asynchronicity/
Credentials for FEM are in 1Pass.
Exercise 13
Last week, we continued our discussion on asynchronous JS and went over some examples from https://github.com/jeremypeter/js-school/blob/master/index-12.html.
We talked about:
- Web/browser API's that browser vendors expose to developers. The
DOM
being the most commonly used browser api. - Browser's provide the asynchronous capabilities of JS. For instance,
setTimeout
isn't a native JS function, but is provided by the browser. - Macro vs micro tasks
Homework
https://github.com/jeremypeter/js-school/tree/master/class-13
Class 15
Today we discussed:
- How to create a new instance of an object using the
new
with a Constructor function - How ES6 Classes are created and used
- Briefly went over what the
this
keyword represents or is referring to
Exercise
https://github.com/jeremypeter/js-school/tree/master/class-15
Extra Credit
- Add the
open
andclose
methods and their functionality to theModal
constructor.
Homework 6
Let's have fun and create our own javascript functions based on native methods.
Create map
function
We want to create a helper function that loops over an array of data, alters the data via a callback function, and returns a new array of altered data based on what's return
ed from the callback. This is what the map
function will do.
var data = [
{ name: 'Steve' },
{ name: 'Mary' },
{ name: 'Barry' },
{ name: 'Jerry' }
];
var names = map(data, function(){
/* ADD FUNCTIONALITY */
});
console.log(names);
// ['Steve', 'Mary', 'Barry', 'Jerry']
/* Complete functionality of `map` */
function map(){
}
Create split
function
We want to be able to split a string up into an array based on a delimiter.
var csv = 'sam,ram,flam,blam';
var arr = split(csv, ',');
console.log(arr);
// ['sam', 'ram', 'flam', 'blam']
function split(str, delimiter){
/* Complete functionality */
}
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. ๐๐๐
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google โค๏ธ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.