New Batch#100 (10th Nov 2021) - Salesforce Admin + Dev Training (WhatsApp: +91 - 8087988044) :https://t.co/p4F3oeQagK

Friday, 6 August 2021

JavaScript Converting Numbers and Math

-- Converting and Checking Numbers ---
// By default numbers are treated as floating by javaScript
// Stores the number in binary (0 or 1) to hold numbers, we see weird results
console.log(10 === 10.0); // true
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false
// Converting to numbers
console.log(Number('10'));
console.log(+'10');
// Parsing
console.log(Number.parseInt('20px', 10)); // 20 Note: 10 is redex base 10 to avoid few issues, When we work with binary use 2
console.log(Number.parseInt('e20')); // NAN
console.log(Number.parseInt('2.5%', 10)); // 2
console.log(Number.parseFloat('2.5%', 10)); // 2.5, having space before will also work
// Check the value is not a number
console.log(Number.isNaN(10)); // false
console.log(Number.isNaN('10')); // false
console.log(Number.isNaN(+'10'));
console.log(Number.isNaN(10 / 0));
// Check the value is a number (this is better way)
console.log(Number.isFinite(10));
console.log(Number.isFinite('10'));
console.log(Number.isFinite(+'10'));
console.log(Number.isFinite(10 / 0));
console.log(Number.isInteger(10));
console.log(Number.isInteger(10.0));
console.log(Number.isInteger(10 / 0));
----------------------------------------------------
== Math and Rounding ===
console.log(Math.sqrt(25));
console.log(25 ** (1 / 2)); // Same as above
console.log(8 ** (1 / 3));
console.log(Math.max(5, 19, 24, 13, 4));
console.log(Math.max(5, 19, '24', 13, 4));
console.log(Math.max(5, 19, '24px', 13, 4));
console.log(Math.min(5, 19, 24, 13, 4));
console.log(Math.PI * Number.parseFloat('5px') ** 2); // Area of circle
// Math.random() --> returns number b/w 0 and 1
// Math.trunc() --> To remove decimal
console.log(Math.trunc(Math.random() * 6) + 1); // value b/w 1 and 6
// Function to generate random number
const randomInt = (min, max) => Math.trunc(Math.random() * (max - min) + 1) + min;
console.log(randomInt(10, 20));
// Rounding Integers
console.log(Math.trunc(14.3)); // cut of decimal part
console.log(Math.floor(14.3)); // cut of decimal part / floor is beter to work with -ve also
console.log(Math.floor(14.9)); // cut of decimal part
console.log(Math.round(14.3)); // round based on < .5 and > .5
console.log(Math.round(14.9));
console.log(Math.ceil(14.3)); // Round to next number
console.log(Math.ceil(14.9));
// Rounding decimal
console.log((3.7).toFixed(0)); // Always returns string
console.log((3.7).toFixed(3));
console.log((3.7554).toFixed(2));
console.log(+(3.7554).toFixed(2)); // To get the number

JavaScript Sorting and Array Creation and Filling

// Sorting - Strings
const certs = ['Admin', 'PD I', 'PD II', 'App Builder'];
console.log(certs.sort()); // Sort Modifies array
console.log(certs);
// numbers also converetd into string and sorted
const transactions = [1000, 3000, 4000, 2000, -898, 3800, -4500];
console.log(transactions.sort()); // [-4500, -898, 1000, 200, 3000, 3800, 4000]
console.log(transactions);
// return < 0; curVal, nextVal (Keep Order)
// return > 0; nextVal, curVal (Swith Order)
// Ascending Order
/*transactions.sort((curVal, nextVal) => {
if(curVal > nextVal) return 1;
if(curVal < nextVal) return -1;
});*/
transactions.sort((curVal, nextVal) => curVal - nextVal);
console.log(transactions);
// Descending Order
/*transactions.sort((curVal, nextVal) => {
if(curVal > nextVal) return -1;
if(curVal < nextVal) return 1;
});*/
transactions.sort((curVal, nextVal) => nextVal - curVal);
console.log(transactions);
-----------------------
== Creating and Filling Array ===
console.log([1, 2, 3, 4, 5, 6, 7]);
console.log(new Array(1, 2, 3, 4, 5, 6, 7));
const arr = new Array(4); // Different behavior when we add one element
console.log(arr); // (4) [empty × 4]
arr.fill(1);
console.log(arr); // fills all values to array elements
arr.fill(1, 2);
console.log(arr);
arr.fill(1, 2, 3); // 1 value from 2 to 3 index
console.log(arr);
//Array.from
const arr2 = Array.from({length: 7}, () => 9);
console.log(arr2);
const arr3 = Array.from({length: 7}, (curVal, i) => i + 1);
console.log(arr3);
------------------------

Cheat Sheet - 


 

Thursday, 5 August 2021

JavaScript Map, Filter, Reduce, Find, Some, Every, flat, flatMap

Data Transfromation: Map, Filter and Reduce
Map----->
* Applies callback function for the current array and puts it into a new array. Example multiply each element in array and put it in new array
Filter----->
* Filter returns a new array containing array elements that matches a specified condition
Reduce----->
* Reduces all the elments in an array into a single value.
--------------
== Map Method ===
const transactions = [1000, 3000, 4000, 2000, -898, 3800, -4500];
const inrtToUsd = 74;
// Recommended the functional programing which is modren way
const transactionsInr = transactions.map(function(trans) {
return (trans / inrtToUsd).toFixed(2);
});
console.log(transactions);
console.log(transactionsInr);
// Same with arrow
const transactionsInrArrow = transactions.map(trans => (trans / inrtToUsd).toFixed(2));
console.log(transactionsInrArrow);
// Same with for Of
const transactionsInr2 = [];
for(const trans of transactions) transactionsInr2.push((trans / inrtToUsd).toFixed(2));
console.log(transactionsInr2);
/*const transDescriptions = transactions.map((trans, i, arr) => {
if(trans > 0)
return `Transaction ${i + 1}: You deposited: ${trans}`;
else
return `Transaction ${i + 1}: You withdrew: ${Math.abs(trans)}`;
});*/
const transDescriptions = transactions.map((trans, i) => {
return `Transaction ${i + 1}: You ${ trans > 0 ? 'deposited' : 'withdrew'}: ${trans}`;
});
console.log(transDescriptions);
------------------------------------------------
== Filter Method ===
// like forEach the below also having index and current arr
const deposits = transactions.filter(function(trans) {
return trans > 0;
});
console.log(deposits);
// Filter with for of loop
const deposits2 = [];
for(const trans of transactions) {
if(trans > 0) deposits2.push(trans);
}
console.log(deposits2);
// With Arrow function
const withdrawls = transactions.filter(trans => trans < 0);
console.log(withdrawls);
------------------------------------------------
== Reduce Method ===
const balance = transactions.reduce(function(accumulator, currentVal, index, curArray) {
return accumulator + currentVal;
},0); // 0 is the accumulator default value
console.log(balance);
// Using for of
let balance2 = 0;
for(const trans of transactions) balance2 += trans;
console.log(balance2);
const boolVals = [true, false, true, true];
// To verify if all the values are valid
const isTrue = boolVals.reduce(function(accumulator, currentVal, index, curArray) {
console.log(accumulator, currentVal, index, curArray);
return accumulator && currentVal;
},true); // true is the accumulator default value
console.log(isTrue)
------------------------------------------------
== Chaining Methods ===
const inrtToUsd2 = 74;
const totDepositsInUsd = transactions
.filter(trans => trans > 0)
.map(trans => Number((trans / inrtToUsd2).toFixed(2)))
.reduce((acc, trans) => acc + trans, 0);
console.log(totDepositsInUsd);
------------------------------------------------
== ES6: Find Method ===
// Unlike filter it returns the first element in an array that satisfy the condition
const firstWithdrawl = transactions.find(trans => trans < 0);
console.log(firstWithdrawl);
------------------------------------------------
== ES6: findIndex Method ===
const firstWithdrawlIndex = transactions.findIndex(trans => trans < 0);
console.log(firstWithdrawlIndex);
------------------------------------------------
== some and every Method ===
// Equality Check
console.log(transactions.includes(1000));
// Some: Conditon Check: To get true or false based on a condition -
const anyDeposit = transactions.some(trans => trans > 0);
console.log(anyDeposit);
// Every: Conditon Check: To get true if every element matches the condition
console.log(transactions.every(trans => trans > 0));
// Seperate callback
const deposit = trans => trans > 0;
console.log(transactions.every(deposit));
console.log(transactions.some(deposit));
console.log(transactions.filter(deposit));
------------------------------------------------
== ES 2019: flat and flatMap Method ===
// flat works for one level deep
const arr = [[1, 2, 3], [4, 5, 6], 7, 8];
console.log(arr.flat());
// flat works for multi level when we give depth
const arrDeep = [[[1, 2], 3], [[4, 5], 6], 7, 8];
console.log(arrDeep.flat()); // Default 1
console.log(arrDeep.flat(2));
// flat map by combining map and flat
let arr1 = ["JS Demo for LWC", "", "Bangalore"];
console.log(arr1.map(x => x.split(" ")));
// [["JS","Demo","for", "LWC"],[""],["Bangalore"]]
console.log(arr1.flatMap(x => x.split(" ")));
// ["JS","Demo","for", "LWC","","Bangalore"]
TO DO: Sorting Arrays and Some other topics

Wednesday, 4 August 2021

JavaScript Array Mehtods and forEach

//-- Array Methods ---------
//-- Slice ------- Don't modify the array
let arr = [1, 2, 3, 4, 5, 6];
console.log(arr.slice(2));
console.log(arr.slice(2, 4));
console.log(arr.slice(-2));
console.log(arr.slice(-1));
console.log(arr.slice(1, -2));
console.log(arr.slice());
console.log([...arr]);
// -- Splice ------- modifies the array, Good to use for delete
// console.log(arr.splice(2));
// To delete
arr.splice(-1); // [1, 2, 3, 4, 5]
arr.splice(1, 2); // Delete 2 elements from the index 1
console.log(arr);
// -- Reverse ----- modifies the array, To reverse the array
const arr2 = ['a', 'b', 'd', 'd', 'e'];
console.log(arr2.reverse());
console.log(arr2);
// -- Concat -----
const letters = arr.concat(arr2);
console.log(letters);
console.log([...arr, ...arr2]);
// -- Join -----
console.log(letters.join('-'));
------------------------------
//-- forEach with Arrays-------------------
const transactions = [300, 4000, -490, 982, -34, 490, 200, -45];
//for(const transaction of transactions) {
for(const [i,transaction] of transactions.entries()) {
// break works here
if(transaction > 0) {
console.log(`You deposited ${transaction}`);
}
else {
console.log(`You withdrew ${Math.abs(transaction)}`); // abs to convert -ve to +ve
}
}
console.log('*************************');
// transactions.forEach(function(transaction) { // Callback function
transactions.forEach(function(transaction, index, array) {
// 1 param: current elmt
// 2 param: index value
// 3 param: array constructed so far
// Order matters but not the name
// break won't work with for each
if(transaction > 0) {
console.log(`You deposited ${transaction}`);
}
else {
console.log(`You withdrew ${Math.abs(transaction)}`); // abs to convert -ve to +ve
}
});
//-- forEach with Maps and Sets -------------------
const currencies = new Map([
['USD', 'United States Dollar'],
['EUR', 'Euro'],
['INR', 'Indian Rupee']
]);
currencies.forEach(function(value, key, map) {
console.log(`${key}: ${value}`);
});
// Set
const currencySet = new Set(['USD', 'EUR', 'INR']);
console.log(currencySet);
currencySet.forEach(function(value, _, map) { // _ is unnecessary variable
console.log(`${value}: ${_}`);
});

JavaScript IIFE and Closures

// Immediately Invoked Function Expressions (IIFE)
const runFn = function() {
console.log('This is running as it is called.');
}
runFn();
// IIFE - function - works with private scope
(function() {
console.log('This is executing automatically. This run only once');
const isPrivate = 1;
var isPublicVal = 5;
})();
// console.log(isPrivate);
// console.log(isPublicVal); // var also works in private scope this gives error
// IIFE - Arrow Function - works with private scope
(() => console.log('This Arrow fn is executing automatically. This run only once'))
();
// let and const works in a private scope and no need to use IIFE unless if you want to use var
{
const isPrivate = 8;
var isPublic = 5;
}
// console.log(isPrivate); // This gives error
console.log(isPublic);
---Closures----------------------------
// Which will be done by javaScript in the background
// A closure makes sure that a function doesn't loose connection to variables that existed at the function's birth place
const bookSlot = function() {
let numOfBookings = 0; // this is remembered in the returned function
return function() {
numOfBookings++;
console.log(`${numOfBookings} slots booked.`);
}
}
const booker = bookSlot();
booker();
booker();
booker();
// One more example
let innerFn;
const outFn1 = function() {
val1 = 20;
innerFn = function() {
console.log(val1 * 10);
};
};
const outFn2 = function() {
val2 = 50;
innerFn = function() {
console.log(val2 * 10);
};
};
outFn1();
innerFn();
outFn2();
innerFn();
// One more closure example
const conductExam = function(numOfCand, wait) {
const perRoom = numOfCand / 2; // Closure Variable
setTimeout(function() {
console.log(`There are 2 rooms, each with ${perRoom} candidates`);
}, wait * 1000);
console.log(`Exam will be started in ${wait} seconds`);
};
const perRoom = 10; // closure is having more priority than the scope chain
conductExam(8,3);

Monday, 2 August 2021

JavaScript Call and Apply and Bind Methods

// Call and Apply and Bind Methods
const jsDevCer = {
name: 'Salesforce Javascript Develoepr',
centerCode: 'BtmCloud',
bookings: [],
book(examCode, name) {
console.log(
`${name} booked a slot for ${this.name} with code: ${this.centerCode}${examCode}`
);
}
};
jsDevCer.book(8987,'Srinu');
const cpqCer = {
name: 'Salesforce CPQ',
centerCode: 'BtmCloud',
bookings: []
};
const book = jsDevCer.book;
// The below code won't work as the this keyword is not available
//book(4433,'Mark');
// call method
book.call(cpqCer,5454,'Steve');
// Apply Method which uses the array
const cerData = [8789, 'Tim'];
book.apply(jsDevCer,cerData);
//Use spread instead of apply
book.call(jsDevCer,...cerData);
--------------------
// Bind Method - returns a function with object as this
const bookCpq = book.bind(cpqCer);
bookCpq(1111,'Will');
// Binding with this and few params
const bookCpq0221 = book.bind(cpqCer,0221);
bookCpq0221('Yash');
// With Event Listeners
document.addEventListener('keydown',bookCpq);
// Partial application
const addTax = (rate, value) => value + value * rate;
console.log(addTax(0.5,100));
const addVat = addTax.bind(null,0.30);
console.log(addVat(50));

JavaScript Function as argument and Function as return type

// First Class functions
// functiions are values or objects (first class citizens)
// Can store functions in variables or properties
// Pass functions as arguments to the other functions
// return functions from functions
// call mehtods on functions
// Function as a argument
const word = function(str) {
return str.replaceAll(' ','').toLowerCase();
};
const upperFirstWord = function(str) {
const [first,...others] = str.split(' ');
return [first.toUpperCase(),...others].join(' ');
};
// Higher-order function
const stringModifier = function(str, fn) {
console.log(`Original String: ${str}`);
console.log(`Modified String: ${fn(str)}`);
console.log(`Modified By: ${fn.name}`);
};
stringModifier('Javascript is the future',upperFirstWord);
stringModifier('Javascript is the future',word);
// Event Listener
const testFn = function() {
console.log('testing');
};
// Accepting callback function
document.addEventListener('click',testFn);
// for each
[1, 2, 3].forEach(testFn);
------------------
// Function returns a new function
const greet = function(greeting) {
return function(name) {
console.log(`${greeting} ${name}`);
};
};
const greetHi = greet('Hi');
greetHi('Srinu');
greetHi('Mark');
greet('Hi')('Guys');
// Above function with arrow (Arrow function returning another arrow function)
const greet2 = greeting => name => console.log(`${greeting} ${name}`);
greet2('Hi')('Folks');

JavaScript Default Params and Passing reference variables as arguments to the function

Default Parameters -
const resources = [];
const createResource = function(
firstName, lastName, email = 'test@test.com'
) {
lastName = lastName || 'Test Name';
const resource = {
firstName,
lastName,
email
};
console.log(resource);
resources.push(resource);
}
createResource('Bob');
createResource('Mark','Benioff','mark@gmail.com');
------------------------------------------------
// Values vs Reference Parameters for a function -
const position = 'SFDC Develoepr';
const resource = {
name: 'Srinu',
job: 'SFDC Develoepr'
};
const addResource = function(posTitle, resource) {
posTitle = 'SFDC Admin+Develoepr';
resource.name = 'Mr. ' + resource.name;
if(posTitle === resource.job) {
alert('Add Resource');
}
else {
alert('Cannot add resource');
}
}
addResource(position,resource);