Giter VIP home page Giter VIP logo

js-school's People

Contributors

jeremypeter avatar

Stargazers

 avatar

Watchers

 avatar  avatar

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-finder (1)

https://www.loom.com/share/2f39b634b01d4471bb5568912abec5b7

Class 16

Items covered in todays class

  • Implemented the open and close 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 our click event
  • How to use getElementsByClassName
  • How to use querySelector

QUIZ

  1. What is a constructor function in JS?
  2. What does the new keyword do?
  3. What is this prototype property?
  4. Are there any benefits to using constructor functions?
  5. 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:

  1. Create a new <button> element
  2. Add a class of close to the button
  3. Add Close as the text for the button
  4. Add/append the close button to the modal container
  5. Inside of the initializeEvents method, add another click 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:

  1. a > f
  2. b
  3. e || d
  4. g == a
  5. g !== b && c
  6. c.length <= f
  7. b || d || (b > a) || e
  8. a === g
  9. c.length
  10. 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

  1. Create a file called requecipe.js to store our library and it's logic, then load the script in your HTML file
  2. Within requecipe.js create a constructor function called Requecipe

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

  1. Create a prototype method on the Requecipe constructor called createQueryString
  2. 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

  1. Create a prototype method on the Requecipe constructor called formatServingTime
  2. 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 is 1h 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;
}
  1. What scope is the name variable in?
  2. What scope is the num variable in?
  3. 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);
  1. What scope is the getName function in?
  2. What scope is the lowercase function in?
  3. What will the console.log(name) return?
  4. 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);
  1. What scopes are being used in the above code (choose all that apply)?
    1. Global
    2. Local
    3. Function
    4. Block
    5. Nested
  2. Why does't console.log(animal) return Dog?

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.

  1. Copy the code to an html file so you can debug using Chrome console
  2. There's a cleanupBadData function declaration I created that you'll need to fill in
  3. 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.

  1. Create a prototype method on the Requecipe constructor called searchRecipes
  2. 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

  1. Loop over the results building up a string of cards
  2. Use information from each result to dynamically set the image, title, time it takes to cook, and the serving size
  3. Add that string of cards to the card container

Homework 11

We learned about:

  • let and const
    • Don't get hoisted.
    • Stay within their current scope.
    • Some developers/tutorials may say to use let over var
  • var
    • Get's hoisted when inside of a block scope that isn't function scope.
  • The difference between function declarations and function expressions.
  • When would someone use a function declaration over a function expression.

Quiz

  1. Which of the following is a function expression and a function declaration?
    A)
    function test1(){}
    B)
    var test1 = function(){}
  2. Why would you use a function expression over a function declaration?
  3. Given the following code, why does console.log(firstCode) log "charlie" when the firstCode variable is contained in a block scope?
     var codes = ['charlie', 'fox', 'alpha'];
    
     if(codes.length > 1) {
         var firstCode = codes[0];
     }
    
     console.log(firstCode);
  4. 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);
  5. Given the following code, why does console.log(data) throw an error?
     const data = [];
    
     data = {};
    
     console.log(data);
  6. 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:

  1. What are at least 2 other ways to create a new data object?
  2. How can we "set" a property of name on the data object to have value timmy? Give at least 2 ways to set an object.
  3. How can we "get" the value of the name property on the data object? Give at least 2 ways to get a value from an object property.
  4. How can we "set" the value of ageVar as a property on the data object with a value of 10 e.g.
    { age: 10 }
    
  5. How do we set duplicate properties on an object? e.g.
    { age: 10, age: 25, age 15 }
    
  6. 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.

  1. Loop over the clutter array
  2. Within the loop, create an if conditional that uses the typeof keyword to check if the current item being is a number
  3. If it's a number push it to the new numbers array
  4. 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

Congratulations on making it this far! Time to add a new feature!! A Load More button!!!

Acceptance Criteria

  1. When a user clicks the Load More button, it should load in more results while maintaining the previous results

Example

ColMPLgJXl

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.loging them for now.

Dev Instructions

  • Create a scripts.js file and link that to your index.html file
  • Add the logic to handle user submissions to the scripts.js file

Acceptance Criteria

  1. When a user enters pizza in the search field and hits the Enter key to trigger a form submission, we should log the results to the console
    M9V02f6Rbu

  2. When a user enters cake and clicks the search button to trigger a form submission, we should log the results to the console
    IVCHu0wVfw

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

  1. Create our own pop and push functions to mimic the functionality of the native Array.pop() and Array.push() methods.
  2. Use a switch statement to return the price for items passed in to the getMenuPrice() 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:

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

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 returned 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 photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.