Thursday, November 12, 2020

Arrays 4 : Callback Methods find() filter() some() every() sort()

 /*
Callback Methods
*/


// const util = {
// findBurgRating: function(singleFeedback) {
// return singleFeedback.comment.includes('burg');
// }
// }

// function findBurgRating(singleFeedback, index, array) {
// return singleFeedback.comment.includes('burg')
// }

//rating => rating.comment.includes('burg')

// find the first rating that talks about a burger with find()
// const burgRating = feedback.find(findBurgRating);
// console.log(burgRating);

function findByWord(word) {
return function(singleFeedback) {
return singleFeedback.comment.includes(word);
}
}

const wordFinder = findByWord('Smoothie');
const findWord = feedback.find(wordFinder);
console.log(findWord);

// find all ratings that are above 2 with filter()

function filterByMinRating(minRating) {
return function (singleFeedback) {
return singleFeedback.rating > minRating;
}
}

const goodReviews = feedback.filter(filterByMinRating(4));
console.table(goodReviews)

// find all ratings that talk about a burger with filter()
const burgRatings = feedback.filter(singleFeedback => singleFeedback.comment.includes('burg'));
console.table(burgRatings)

// Remove the one star rating however you like!
// Para mostrar solamente los que son superiores a 1. Esto puede ser para un dropdown donde elijas los ratings de que numero para arriba o abajo quieres ver.
const legitRatings = feedback.filter(single => single.rating !== 1);
console.table(legitRatings);

// check if there is at least 5 of one type of meat with some()
// Cuando quieres saber si hay por lo menos un numero de algo. GIves a boolean.
const isThereEnoughOfAtLeastOneMeat = Object.values(meats).some(meatValue => meatValue >= 5);
console.log(isThereEnoughOfAtLeastOneMeat);


// make sure we have at least 3 of every meat with every()
// Cuando quieres saber si hay por lo menos un numero de TODO. GIves a boolean.
const isThereEnoughOfEvery = Object.values(meats).every(meatValue => meatValue >= 3);
console.log(isThereEnoughOfAtLeastOneMeat);


// sort the toppings alphabetically with sort()
const numbers = [1,2,100,3,200,400,155]
// const numbersSorted = numbers.sort(function(firstItem, secondItem) {
// if(firstItem > secondItem) {
// return 1;
// } else if(secondItem > firstItem) {
// return -1;
// } else {
// return 0;
// }
// });

const numbersSorted = numbers.sort(function(firstItem, secondItem) {
return firstItem - secondItem; //in forward order
// return secondItem - firstItem; //in inverse order
});
console.log(numbersSorted);

// sort the order totals from most expensive to least with .sort()
function numberSort(a, b) {
return b - a;
}

console.log(orderTotals.sort(numberSort));
// Sort the prices with sort()

const productsSortedByPrice = Object.entries(prices).sort(function(a, b) {
const aPrice = a[1];
const bPrice = b[1]
return bPrice - aPrice;
});
console.table(productsSortedByPrice);

Arrays 3 : Instance Methods pop() push() shift() unshift() slice() splice() indexOf() lastIndexOf() includes()

 /*
Instance Methods
*/

pop() push() shift() unshift() slice() splice() indexOf() lastIndexOf() includes()


// Display all bun types with " or " - use join()

// We have a string "hot dogs,hamburgers,sausages,corn" - use split() to turn it into a string
const foodString = "hot dogs,hamburgers,sausages,corn";
// console.log(foodString.split(','));
// console.log([...foodString]);

// console.log(foodString.split(''));
// console.log([...foodString]);
// These two work the same, it's because you're splitting with nothing.

// take the last item off toppings with pop()
const lastItem = toppings.pop();
// console.log(lastItem);

// add it back with push()
const t2 = toppings.push(lastItem);
// console.log(t2);

// take the first item off toppings with shift()
const firstItem = toppings.shift();
// console.log(firstItem);

// add it back in with unshift()
const t3 = toppings.unshift(firstItem);
// console.log(t3);

// Do the last four,but immutable (with spreads and new variables)
let newToppings = toppings.slice(0, toppings.length - 1);
newToppings = [...newToppings, toppings[toppings.length - 1]];
// console.log(newToppings);

newToppings = toppings.slice(1, toppings.length - 1);
newToppings = ['Mushrooms', ...newToppings];
// console.log(newToppings);

// Make a copy of the toppings array with slice()
const toppingsCopy = toppings.slice(0) // end is optional
// console.log(toppingsCopy);

// Make a copy of the toppings array with a spread
const toppingsCopy2 = [...toppings] // end is optional
// console.log(toppingsCopy2);

// take out items 3 to 5 of your new toppings array with splice()
// console.log(newToppings);
newToppings = newToppings.splice(2, 3);
// console.log(newToppings);

// find the index of Avocado with indexOf() / lastIndexOf()
const avoIndex = toppings.indexOf('Avocado');
// console.log(avoIndex);

const avoIndex2 = toppings.lastIndexOf('Avocado');
// console.log(avoIndex2);


// Check if hot sauce is in the toppings with includes()
const isInToppings = toppings.includes('Hot Sauce');
// console.log(isInToppings);
// add it if it's not
if (!isInToppings) {
toppings.push('Hot Sauce')
}
// console.log(toppings);

// flip those toppings around with reverse()

toppings.reverse();
// console.log(toppings); 

Arrays 2 : Static Methods Array.of() Array.from() Array.isArray() Object.entries() Object.keys() Object.value()

Array.of() Array.from() Array.isArray() Object.entries() Object.keys() Object.value()


// Array.of(); // Make an array from its arguments

// Array.of('Wes', 'Kait');
// Make an array from a String or Iterable.

// How to create a Range from x to y:

function createRange(start, end) {
const range = Array.from({ length: end - start + 1}, function(_item, index) {
return index + start;
})
return range;
}

// Make a function that creates a range from x to y with Array.from();
const myRange = createRange(3, 7424);

// Check if the last array you created is really an array with Array.isArray();
console.log(Array.isArray(myRange));

// Take the meats object and make three arrays with Object.entries(), Object.keys, Object.values()

// console.log(Object.entries(meats));
// console.log(Object.keys(meats));
// console.log(Object.values(meats));

//This one is already destructured:
Object.entries(meats).forEach(([key, value]) => {
// const key = entry[0];
// const value = entry[1];
// const [key, value] = entry;
 console.log(key, value);
});

Arrays 1

// How to create an Array. How to make a new array and add something in the middle.

const bikes = ['Bianchi', 'Miele', 'Panasonic', 'Miyata'];

 const newBikes = [
...bikes.slice(0, 2),
'Benotto',
...bikes.slice(2)
]

// How to add something by spreading:

const names2 = [...names, 'Lux'];
const names3 = ['Poppy', ...names]

// slice is immutable
// returns shallow copy, the end is not inclusive


// splice is mutable
// take the item out of the original array
// start and how many to go for

// How to find the index of something by its id:

function deleteComment(id, comments) {
const commentIndex = comments.findIndex(comment => comment.id === id);
return [
...comments.slice(0, commentIndex),
...comments.slice(commentIndex + 1),
]}

// How to find the index of something by the exact thing inside the array:

const kaitIndex = names.findIndex(name => name === 'Kate');
console.log(kaitIndex);

Tuesday, September 22, 2020

Module 5: Prevent Default and Form Events

// Prevent default.

wes.addEventListener('click'), function(event) {
    const shouldChangePage = confirm(
        'This website might be malicious!, do you wish to proceed?'
    );
        if (!shouldChangePage) {
               event.preventDefault();
    }
});

const signupForm = document.querySelector('[name="signup"]');

signupForm.addEventListener('submit', function(event) {
    const name = event.currentTarget.name.value;
    if (name.includes('chad')) {
        alert('Sorry bro');
        event.preventDefault();
    }
});

function logEvent(event) {
    console.log(event.type);
    console.log(event.currentTarget.value);
}

signupForm.name.addEventListener('keyup', logEvent);

'keyup'
'keydown'
'focus'
'blur'

Tuesday, March 3, 2020

Module 2: Functions (Different ways to Declare Functions)

console.log('Buya!')

//First Class Citizens

const age = 100;
const cool = true;


//Anon function
// function (firstName) {
// return `Dr. ${firstName}`;
// };

//Cannot run before initializing the function as a const.
// doctorize('Wes');
// console.log(doctorize('Wes')); <-- This works.

//Function Expression
const doctorize = function(firstName) { // <-- This functions are not hoisted.
doesntExist();
return `Dr. ${firstName}`;
};

//Arrow functions <-- they are annonymous functions(always in a variable)

// function inchToCM(inches) {
// const cm = inches * 2.54;
// return cm;
// }

//Function as it was:
// function inchToCM(inches) {
// const cm = inches * 2.54;
// return cm;
// }

// Step 1:
// const inchToCM = function(inches) {
// const cm = inches * 2.54;
// return cm;
// }

// Step 2:
// const inchToCM = function inchToCM(inches) {
// return inches * 2.54;
// }

// Step 3:
// const inchToCM = (inches) => {
// return inches * 2.54;
// }

// Step 4:
// const inchToCM = (inches) => inches * 2.54;

// Step 5:
const inchToCM = inches => inches * 2.54;

//Steps to create an arrow function:
// 1. Make it a function in a variable. Name the function at variable level.
// 2. Remove the const for the return and just return the resolution of the expression
// 3. Remove function text and place fat-arrow on the right side of parenthesis.
// 4. Remove explicit return and the brackets.
// 5. If there's only one argument remove parenthesis

// function add(a, b = 3) {
// const total = a + b;
// return total;
// }

const add = (a, b = 3) => a + b;

// function makeABaby(first, last) {
// const baby = {
// name: `${first} ${last}`,
// age: 0
// }
// return baby;
// }

// const makeABaby = (first, last) => {
// const baby = {
// name: `${first} ${last}`,
// age: 0
// }
// return baby;
// }

const makeABaby = (first, last) => ({ name: `${first} ${last}`, age: 0 });

// const percentageChange = (num1, num2) => `${ parseInt( ((num2 - num1) / num1) * 100 ) }%`;

const percentageChange = (num1, num2) => `${ ( ((num2 - num1) / num1) * 100 ).toFixed(2) }%`;

// IIFE
// Immediately Invoked Function Expression
// Wrap a function in parenthesis and then add (); at the end.

// (function() {
// console.log('Running the annon function')
// return 'You are cool';
// })();

(function(age) {
console.log('Running the annon function');
console.log( `You are cool and age ${age}`)
return `You are cool and age ${age}`;
})(10);


// Method
// A function that lives inside of an object.
// console is an object
// log is the function

const wes = {

name: 'THIS NAME: Wes Bos',
sayHi: function() {

console.log(this.name);

console.log('Hey Wes');
return 'Hey Wes';
},

yellHi() {
console.log('HEY WESSSS');
},

whisperHi: () => {
console.log('hi wes im a mouse')
}

}

//Callback Functions

const button = document.querySelector('.clickMe');

function handleClick() {
console.log('Great clicking!')
}

button.addEventListener('click', handleClick);

button.addEventListener('click', function() {
console.log('damn!');
});

setTimeout(wes.yellHi, 1000);

Thursday, December 12, 2019

Module 5: targets, bubbling, propagation and capture

The event object.
To access it we modify our callback, our handler, we modify it to accept a parameter.

function handleBuyButtonClick(event) {
   console.log('You are buying it!');
  console.log('event');
}

buyButtons.forEach(function(buyButton) {
   buyButton.addEventListener('click', handleButtonClick);
});

//// the same but different

function handleBuyButtonClick(event) {
   console.log('You are buying it!');
  console.log('event.target'); // with that it will show you which button was clicked. // you can access anything about that event using event.target
}

//So if you want to see the TextContent inside the button that was clicked:
Add
const button = event.target;
inside the function, then
console.log(button.textContent);

buyButtons.forEach(function(buyButton) {
   buyButton.addEventListener('click', handleButtonClick);
});

////the same but different

For this to work you first have to add data-price="x-amount of dollars" to the html.

function handleBuyButtonClick(event) {
   console.log('You are buying it!');
  console.log('event.target.dataset.price'); // with that it will show you which button was clicked. //wrap it with parseFloat() to get a number since the regular output is a string.
}

buyButtons.forEach(function(buyButton) {
   buyButton.addEventListener('click', handleButtonClick);
});

//

another way is to use event.currentTarget
console.log(event.currentTarget);

What is the difference?
Are they the same?
The difference comes when you have nested elements.

In most cases you want to use event.currentTarget
to be precise.

Clicking on multiple things at once:
PROPAGATION

if you want to stop propagation

event.stopPropagation();

///

window.addEventListener('click', function(event) {
console.log(event.target);
});

//

There is a way to flip that.
capture:

window.addEventListener('click', function(event) {
console.log(event.target);
}, { capture: true });

//

photoEl.addEventListener('mousemove', function(e) {
   console.count(e.currentTarget);
});

photoEl.addEventListener('mouseenter', function(e) {
   console.count(e.currentTarget);
});


//


photoEl.addEventListener('mouseenter', function(e) {
   console.count(e.currentTarget);
   console.count(this);
});
//look to the left of the dot.



Module 5: Event Listener

const butts = document.querySelector('.butts');
const coolButton = document.querySelector('.cool');

const hooray = () => console.log('Hooray!');
//This is an arrow function that can also be used as an eventhabdler.

function handleClick() {
   console.log('πŸ›It got clicked!');
}

butts.addEventListener('click', handleClick);
coolButton.addEventListener('click', handleClick);

//if you want to remove it then you have to do this:
//There's no way to remove an anonymous function. You must use a named function in order to unbind it.

butts.removeEventListener('click', handleClick);

//
//Listen on multiple items.

const buyButtons = document.querySelectorAll('button.buy');

//You have to forEach() each element. A method Run a function for each item in our node list.
buyButtons.forEach(functions(buyButton) {
  console.log(buyButton);
  console.log('Binding the buy button');
buyButton.addEventListener('click', buyItem);
})

//or

function handleBuyButtonClick(anythingWeWant) {
anythingWeWant.addEventListener('click', buyItem);
}

buyButtons.forEach(handleBuyButtonClick);


//arrow function form//you cannot unbind it since it is an anonymous function.
buyButtons.forEach((button) => {
button.addEventListener('click', () => {
   console.log('you clicked it');
});
});

Wednesday, December 11, 2019

Tuesday, December 10, 2019

Module 4: Traversing and Removing Nodes

const wes = document.querySelector('.wes');

console.log(wes.children);
//Will show just the child elements.
wes.firstChildElement;
wes.lastElementChild;
wes.previousElementSibling;
wes.nextElementSibling;
wes.parentElement;

console.log(wes.childNodes);
//Will show all the nodes under the element.

Module 4: HTML from Strings and XSS

item.innerHTML = `
<h1> Hey how are ya?</h1>
`;
//Change the getter to a setter and put the HTML code inside.

const width = 500;
const src = `https://pic.jpg${width}`;
const desc = `cute pup`;
const myHTML = `
<div class="wrapper">
  <h2>${desc}</h2>
  <img src="${src}" alt="${desc}"/>
</div>
`;

item.innerHTML = myHTML;
//THE HTML IS JUST A STRING.
//We can't do class things like methods and stuff. it's not an element. It becomes an element once it's dumped.
//You first have to dump it first and then do stuff after the fact.

////The other option is:

//turn a string into a DOM element

const myFragment = document.createRange().createContextualFragment(myHTML);

//This fragment is turned into DOM elements and now you can do things like:
myFragment.querySelector('img');

document.body.appendChild(myFragment);

Monday, December 9, 2019

Module 4: Creating HTML

document.createElement(tagName[, options]);

const myParagraph = document.createElement('p');
//we created it but it's only in memory. it won't show.

if you want to add attributes. Then
myParagraph.textContent = 'I am a P';
myParagraph.classList.add('special');

const myImage = document.createElement('img');

myImage.src = 'http://www.pics.jps'';
myImage.alt = 'Nice Photo';

const myDiv = document.createElement('div');
myDiv.classList.add('wrapper');

how do the add them to the page?

if you just want to dump it straight into the body
document.body.appendChild(aChild);
//method to add a Node to the end of the list

document.body.appendChild(myParagraph);

document.body.appendChild(myDiv);
myDiv.appendChild(myParagraph);
myDiv.appendChild(myImage);

It causes a repaint on the browser. You're triggering three sequential appendChild();
So what you can do instead:

myDiv.appendChild(myParagraph);
myDiv.appendChild(myImage);

and then

document.body.appendChild(myDiv);

That will just cause one.

append() another option.


const heading = document.createElement('h2');
heading.textContent = 'Cool things';

myDiv.appendChild(heading);
myDiv.insertAdjacentElement('afterbegin', heading);

const li1 = li5.cloneNode();
list.insertAdjacentElement('afterbegin', li1);
//

const li1 = li5.cloneNode(true);
li1.textContent = 'one';
list.insertAdjacentElement('afterbegin', li1);
//

Module 4: Build in and Custom Data Attributes

Attributes
//anything that's provided to an element other than the info
//They work like properties.

pic.alt = 'Cute Pup'; //setter
//don't say Image of or Picture of.

pic.width = 200;

console.log(pic.alt); //getter

console.log(pic.naturalWidth); //getter
//you have to wait for the image to download before you can get the width.

window.addEventListener('load', function() {
console.log(pic.naturalWidth);
}
//This will wait for everything to load before running the function.

pic.window.addEventListener('load', function() {
console.log(pic.naturalWidth);
}
//You can do that for just one pic and wait for it to load.

pic.width = 500;
//change the width attribute.

pic.getAttribute('alt');
console.log()

pic.setAttribute('alt', 'really cute pip');
//

pic.hasAttribute
//returns if it has an attribute. true or false if it has been set.

attach a data attribute
data-name="blah"

to access them:
classname.dataset

custom.addEventListener('click', function() {
alert(`Welcome ${custom.dataset.name `);
});

Module 4: Working with classes

console.log(pic.classList);
//A Dom token list. Array of all the classes that are on that list.

pic.classList.add('open');
pic.classList.remove('cool');
pic.classList.toggle('round');
//Add, remove or toggle a class from an element.
//Create a CSS class that will change it when doing something.

pic.addEventListener('click', toggleRound);
//This will run the function toggleRound once the pic is clicked:

function toggleRound() {
 pic.classList.toggle('round');
}
//function that adds and removes the roundness if you round it on the CSS.

A lot of Javascript interaction will be adding or removing classes to elements.



Module 4: Element Properties and Methods(getters and setters)

Getters and Setters

console.dir(element);
//will show you the object properties.

element.textContent
//get the text inside the element. This is the newer of the methods. It shows you also the hidden ones.

element.innerText
//Just the text inside without the hidden elements.

element.innerHTML
element.outerHTML
//gets the HTML inside and outside the element.

pizzaList.textContent = `${pizzaList.textContent} pizzaπŸ•`;
//Include the text pizza. But it's slow. The alternative:

pizzaList.insertAdjacentText('beforeend', 'pizza');
//It inserts the text pizza before the end. It takes the place first:
beforebegin
afterbegin
beforeend
aftereend
Then the element you want to add.

Place to find all the different properties:
https://developer.mozilla.org/en-US/docs/Web/API/Element



Module 4: Selecting Elements on the Page or DOM

const p = document.querySelector('p');
// Create a constant that will get the first 'p' element on the page. Works like CSS selector. #div p

document.addEventListener('DOMContentLoaded', function);
//make it wait until the DOMContent is loaded to start the function.

A NodeList is not an Array. It doesn't have the methods.

const p = document.querySelectorAll('p');
//get or select all the p elements on the page.


Module 4: The DOM

window.location
//object full of information.

innerWidth
//how wide is the window

document
//all of the document

navigator
//gives you information about the device, webcam and stuff


Arrays 4 : Callback Methods find() filter() some() every() sort()

  /* Callback Methods */ // const util = { // findBurgRating: function(singleFeedback) { // return singleFeedback.comment....