/***************************************************************
* Array utilities
***************************************************************/
//* Shallow and Deep Array Cloning
const drinks = [['Lemonade', 99], ['Lime', 99], ['Peach', 89]];
// Copy - copy by reference which means its mutable
const drinksClone1 = [...drinks];
const drinksClone2 = drinks.slice();
const drinksClone3 = Array.from(drinks);
// Deep clone
const drinksDeepClone = JSON.parse(JSON.stringify(drinks));
/**
* Merging Arrays
*/
const drinks = [['Lemonade', 99], ['Lime', 99]];
const newDrinks = ['Peach', 89];
// ES5
const merged1 = drinks.concat(newDrinks); // immutable
// ES6
const merged2 = [newDrinks, ...drinks]; // immutable
/**
* Adding Array Elements
*/
const drinks = ['Lemonade', 'Lime', 'Peach'];
console.log([...drinks, 'Beer']); // immutable
drinks.push('Cola'); // mutable
/**
* Removing Array Elements
*/
// remove the beginning of the array
const removedFirst = drinks.shift() //mutable
// remove the end of the array
const removedEnd = drinks.pop() //mutable
const index = drinks.length - 1; // remove the last item of the array
// using slice will allow to remove an array item from anywhere
const newDrinks = [...drinks.slice(0, index), ...drinks.slice(index + 1)]; // immutable
/***************************************************************
* Try/Catch - handling error without freeze the program
***************************************************************/
const convertToPound = dollar => {
// check if the argument that passed in is an actual number
if (typeof dollar === 'number') {
return dollar * 0.81;
} else {
throw Error('The amount passed in need to be in number')
}
}
try {
convertToPound('five')
} catch (error) {
console.log(error);
}
let json = '{age: 30}';
try {
let user = JSON.parse(json);
// check if there's no user object that has a property of 'name'
// we're expecting the data that comes back from the server to have 'name'
if (!user.name) {
throw new SyntaxError('Incomplete data: no name')
}
// this line here won't execute if above is true
console.log(user.name)
} catch (e) {
console.log('JSON Error: ', e.message)
}
/***************************************************************
* Object
***************************************************************/
// Removing Object Properties
const drink = {
id: 'xhs8Pla',
name: 'Lemonade',
price: {
sale: 99,
full: 129,
},
};
// delete it permanently - slow performance
delete drink.id; // mutable
// well performance
drink.id = undefined; // mutable
// rest operator - delete
const { price, ...rest } = drink; // immutable
console.log(price, rest, drink);
// Shallow and Deep Object Cloning
const drinkCloneOne = Object.assign({}, drink);
const drinkCloneTwo = { ...drink };
// deep copy
const drinkStringified = JSON.stringify(drink); // send to the server as string
const drinkClone = JSON.parse(drinkStringified); // receive from the server and convert to an object
// Merging Objects
const drink = {
id: 'xhs8Pla',
name: 'Lemonade',
};
const price = {
sale: 99,
full: 129,
};
const mergeObjES5 = Object.assign({}, drink, { price: price });
// mergeObj = {
// "id": "xhs8Pla",
// "name": "Lemonade",
// "price": {
// "sale": 99,
// "full": 129
// }
// }
const mergeObjES6 = {..drink, ...{ price } };
// mergeObj = {
// "id": "xhs8Pla",
// "name": "Lemonade",
// "price": {
// "sale": 99,
// "full": 129
// }
// }
// Type-Checking Object
// https://ultimatecourses.com/course/javascript-basics/correctly-type-checking-objects
const drink = {
id: 'xhs8Pla',
name: 'Lemonade',
price: {
sale: 99,
full: 129,
},
};
function getType(obj) {
return Object.prototype.toString
.call(obj)
.slice(8, -1)
.toLowerCase();
}
console.log(typeof drink); // object
console.log(typeof []); // object
console.log(typeof null); // object
console.log({} instanceof Object); // true
console.log([] instanceof Object); // true
console.log(getType(drink)); // object
console.log(getType(null)); // null
console.log(getType([])); // array
// Imperative Object Iteration
const drink = {
id: 'xhs8Pla',
name: 'Lemonade',
price: {
sale: 99,
full: 129,
},
};
const drinkWithId = Object.create(drink); // create a new object of an existing prototype
drinkWithId.id = 'xhs8Pla';
// for..in
for (const prop in drink) {
const value = drink[prop];
if (Object.prototype.toString.call(value) === '[object Object]') {
for (const key in value) {
console.log(key);
}
}
}
for (const prop in drinkWithId) {
if (drinkWithId.hasOwnProperty(prop)) {
console.log(prop, drinkWithId[prop]);
}
}
// Declarative Object Iteration
Object.keys(drink).forEach(function (prop) {
console.log(drink[prop]);
});
/***************************************************************
* Callbacks
***************************************************************/
let objs = [
{ name: 'James', score: 100, school: 'East' },
{ name: 'Steve', score: 33, school: 'West' },
{ name: 'Gabby', score: 43, school: 'East' },
{ name: 'Rachel', score: 78, school: 'South' }
];
let processObj = function (data, callback) {
for (let index = 0; index < data.length; index++) {
const element = data[index];
if (element.school.toLowerCase() === 'east') {
if (typeof callback === 'function') {
callback(element);
}
}
}
}
processObj(objs, function (obj) {
if (obj.score > 40) {
console.log(obj.name) // James, Gabby
}
});
const determineTotal = () => {
let total = 0;
let count = 0;
processObj(objs, function (obj) {
total += total + obj.score;
count++;
});
console.log('Total score: ', total, 'Total count: ', count);
};
determineTotal(); // Total score: 243 Total count: 2