Skip to content

Instantly share code, notes, and snippets.

@PetraSp
Created January 10, 2020 16:37
Show Gist options
  • Select an option

  • Save PetraSp/a9415463f15c6098dbc9af053704bd59 to your computer and use it in GitHub Desktop.

Select an option

Save PetraSp/a9415463f15c6098dbc9af053704bd59 to your computer and use it in GitHub Desktop.
colors.forEach(function(color) {console.log(color) })
var numbers = [1,2,3]
var sum = 0;
numbers.forEach(adder)
function adder(num) {
sum += num
return sum
}
email.forEach(function(email){
deleteEmail(email)
}
var cars = [
{name: 'Buick', price: 'cheap},
{name: 'Camaro', price: 'expensive'}
]
arr = cars.map(car => car.price)
********
function pluck(array, property) {
return array.map(item => item[property] )
}
var person = { name: 'Bill', age: 28 }
person["name"]
****
var products = [
{ name: 'celery', type: 'vegetable' },
{ name: 'banana', type: 'fruit' },
{ name: 'apple', type: 'fruit' },
{ name: 'beet', type: 'vegetable' }
]
var filteredProducts = [];
for (var i = 0; i < products.length; i++) {
if (products[i].type === 'fruit') {
filteredProducts.push(products[i])
}
}
filteredProducts;
products.filter(product => product.type === 'fruit')
var post = {id: 4, title: 'New Post'};
var comments = [
{postId: 4, content: 'new Post'},
{postId: 3, content: 'ok post'},
{postId: 4, content: 'not bad'}
]
function commentsForPost(post, comments){
return comments.filter(comment => comment.postId === post.id)
}
function reject(array, iteratorFunction) {
return array.filter(item => !iteratorFunction(item));
}
function Car(model) {
this.model = model
}
var cars = [
new Car('Buick'),
new Car('Camaro'),
new Car('Focus')
]
cars.find(car => car.model === 'Focus')
this.state.hosts = this.getHostsList()
.map(host => (new Host({ name: host, apps: this.getTopAppsByHost(host) })));
var posts = [ {id: 1, title: 'New Post' }, {id: 2, title: 'Old Post'} ]
var comment = { postId: 1, content: 'Great Post' };
postForComment = (posts, comment) => {
posts.find(post => post.id === comment.postId)
}
postForComment(posts, comment)
Address: "forum.com/posts/45"
const posts = [{}, {}]
const postId = getIdFromUrl()
posts.find(post => post.id === postId)
***** Reduce:
initial value/starting value: 0
var nums = [1,2,3]
var sum = 0;
nums.reduce((sum, number) => { return sum + number},0)
var primaryColors = [{color: 'red'}, {color: 'yellow'}, {color: 'blue'} ]
primaryColors.reduce((previous, primaryColor) => { previous.push(primaryColor); return previous }, []);
function balancedParens(string) {
return string.split("").reduce(previous, char) {
if (previous < 0) {return previous}
if (char === "(") {return ++previous;}
if (char === ")") {return --previous;}
return previous
}, 0)
}
balancedParens("()))") // returns false
var trips = [{ distance: 34 }, { distance: 12 } , { distance: 1 }];
var totalDistance;
totalDistance = trips.reduce((previous, trip) => {
return previous + trip.distance;
}, 0) ;
var desks = [
{ type: 'sitting' },
{ type: 'standing' },
{ type: 'sitting' },
{ type: 'sitting' },
{ type: 'standing' }
];
var deskTypes = desks.reduce(function(previous, desk) {
if (desk.type === 'sitting') { ++ previous.sitting}
if (desk.type === 'standing') { ++ previous.standing}
return previous;
}, { sitting: 0, standing: 0 });
function getMsg() { const year = new Date().getFullYear(); return `The year is ${year}`; }
function getMsg() { const year = new Date().getFullYear(); return `The year is ${new Date().getFullYear()}`; }
function doubleMessage(number) {
return `Your number doubled is ${(2 * number)}`;
}
const add = (a,b) => {
return a + b
}
add(7,3);
const team = {
members: ['Jane', 'Bill'],
teamName: 'Super Squad',
teamSummary: function() {
return this.members.map(member => {
return `${member} ${this.teamName}`
})
}
}
team.teamSummary();
Arrow functions aren't always the solution
name: 'Alex',
getName: function(name) {
return this.name;
}
};
profile.getName();
function createBookShop(inventory) {
return {
inventory: inventory,
inventoryValue: function() {
return inventory.reduce((total, book) => total + book.price, 0)
},
priceForTitle: function(title) {
return this.inventory.find(book => book.title === title).price;
}
};
}
const inventory = [
{title: 'Harry Potter', price: 10}, {title: 'Eloquent Javascript', price: 15 }
];
const bookShop = createBookShop(inventory);
bookShop.inventoryValue();
bookShop.priceForTitle('Harry Potter');
!! inventory: inventory, can be omitted; change to inventory
!! inventoryValue: function() { , : and function word can be omitted, change to
inventoryValue() {
refactor from:
const color = 'red';
const Car = {
color: color,
drive: function() {
return 'Vroom!';
},
getColor: function() {
return this.color;
}
};
to:
const color = 'red';
const Car = {
color: color,
drive() {
return 'Vroom!';
},
getColor() {
return this.color;
}
};
DEFAULT FUNCTION ARGUMENTS
function makeAjaxRequest(url, method='GET')
function sum(a=0, b=0) {
if (a === undefined) {
a;
}
if (b === undefined) {
b;
}
return a + b;
}
function addOffset(style={}) {
if (!style) {
style;
}
style.offset = '10px';
return style;
}
REST and SPREAD
rest:
(...numbers) => changes string to an array
const defaultColors = ['yellow', 'blue', 'red']
const useFavoriteColors = ['orange', 'purple'];
const fallColors = ['fire red', ]
const colors = ['blue', ...fallColors, ...defaultColors, ...useFavoriteColors]
console.log(colors)
function validateShoppingList(...items) {
if(items.indexOf('milk') < 0) {
return ['milk', ...items]
}
return items
}
validateShoppingList('oranges','butter', 'flour')
function product(...numbers) {
return numbers.reduce(function(acc, number) {
return acc * number;
}, 1);
}
product([a,b,c,d,e]);
refactor the following:
function unshift(array, a, b, c, d, e) {
return [a, b, c, d, e].concat(array);
}
function unshift(array, ...items) {
return [...items, ...array];
}
var savedFiled = {
format: 'jpg',
name: 'repost',
size: 10101
}
function fileSummary(file){
return `${file.name} is in ${file.format} of the size of ${file.size}.`
}
fileSummary(savedFiled)
using destructuring refactor to:
var savedFiled = {
format: 'jpg',
name: 'repost',
size: 10101
}
function fileSummary({format, name, size}, {color}){
return `${name} is in ${format} of the size of ${size}.`
}
fileSummary(savedFiled, {color: 'red'})
Destructuring array: destructuring property vs item in an array
const companies = [
'Google',
'Facebook',
'Uber'
]
const [name, name1, name2] = companies;
name
typeof(name2) // string
const {length} = companies;
const [firstItem] = companies
vs
const firstItem = companies[0]
const [name, name2, ...rest] = companies
name
name2
rest
const companies = [
{name: 'Google', location: 'Mountain View'},
{name: 'Facebook', location: 'Menlo Park'},
{name: 'Uber', location: 'SF'}
]
const [{location}] = companies
location
const Google = {
locations: ['Mountain View', 'New York', 'London']
}
const {locations: [location]} = Google
location
function signUp ({username, password, email}){
console.log(email)
}
const user = {
username: 'myUsername',
password: 'myPassword',
email: '[email protected]'
}
signUp(user)
const profile = {
title: 'Engineer',
department: 'Engineering'
};
function isEngineer({title, department}) {
return title === 'Engineer' && department === 'Engineering';
}
const points = [
[4,5],
[10,1],
[0,40]
]
points.map(([x,y]) => {
return {x: x, y: y};
})
const classes = [
[ 'Chemistry', '9AM', 'Mr. Darnick' ],
[ 'Physics', '10:15AM', 'Mrs. Lithun'],
[ 'Math', '11:30AM', 'Mrs. Vitalis' ]
];
const classesAsObject = classes.map(([subject, time, teacher]) => {
return {subject, time, teacher};
});
class Car {
constructor({title}) {
this.title = title
}
drive() {
return 'wroom'
}
}
const car = new Car({title: 'Toyota'})
car.drive();
car;
class Monster {
constructor(options){
this.health = 100;
this.name = options.name;
}
}
class Snake extends Monster {
bite(targetSnake) {
targetSnake.health -= 10;
}
}
Promises
3 states of Promises
unresolved - waiting for something to finish
resolved - something finished and it all went ok - callback - then
rejected - something finished and it went bad - callbacks - catch
let promise = new Promise((resolve, reject) => {resolve()});
promise
.then(()=> console.log('finally finished'));
.then(()=> console.log('i was also ran'));
.catch(()=> console.log('uh oo'));
let promise7 = new Promise((resolve, reject) => {setTimeout(()=> {resolve()},3000);});
url = '';
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
chaining is possible!!!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment