Learn how to detect if the user is online or offline and handle events if a change in the online/offline stateĀ occurs.
We can detect if the user is online or offline by using the online property on the navigator object which will return true if the user is connected to the internet, otherwise it returns false.
Additionally, online and offline events will be triggered if the user’s internet connections state changes. So we can add an online and offline event listener to the window and perform respective actions based on the online and offline state.
This will add a circle inside the dice div. Now, the dice container looks like:
Now, letās make the dot container appear on the center of the dice container. For that, we need to make the first-face as flexbox and apply:
justify-content:center ā will make the dot align to the center of the main axis (horizontal).
align-items:center ā will make the dot align to the center of the cross axis (vertical).
.first-face {
display: flex;
justify-content: center;
align-items: center;
}
Second Face
Second face of theĀ die
Now, we need create a die with two dotsāāāone dot at the top-left corner and another at the bottom-right corner.
<div class="dice second-face">
<span class="dot"> </span>
<span class="dot"> </span>
</div>
Make the second face as flex, and add:
justify-content: space-between ā This will place the children at the beginning and the end of the flex-container.
.second-face{
display: flex;
justify-content : space-between;
}
The above code will create a dice like this:
The first dot is in the correct place: the top-left corner. Now, we need to align the second dot to the bottom-right corner. For that, apply the align-self property to the second dot of the die.
align-self: flex-end ā will align the item to the end of the flex container.
.second-face .dot:nth-of-type(2) {
align-self: flex-end;
}
Third Face
For achieving the third face, weāll have three dots: one at the top left, one at the center, and one at the bottom right of the die.
We can achieve the third-face by placing an another dot center to the second-face.
justify-content: space-between ā This will place the children at the beginning and the end of the flex-container.
.second-face{
display: flex;
justify-content : space-between;
}
Now, we need to make the last dot (third dot) thatāll be placed in the bottom-right.
.second-face .dot:nth-of-type(3) {
align-self: flex-end;
}
Align the middle dot (second dot) at the center of the parent.
.second-face .dot:nth-of-type(2) {
align-self: center;
}
If we want the first dot in the top-right and the last dot in the bottom-left, then change the first dotās align-self to flex-endāāāautomatically the third dot will be placed to the bottom-left because the default property of align-self is flex-start.
Third faceĀ altered
.third-face .dot:nth-of-type(1) {
align-self :flex-end;
}
.third-face .dot:nth-of-type(2) {
align-self :center;
}
Fourth Face
In our fourth face, we can split it in two rows, each row containing two columns. One row will be at flex-start, and another will be at flex-endĀ .
Apply all of the properties applied toĀ .fourth-face andĀ .fourth-faceĀ .column toĀ .fifth-face andĀ .fifth-faceĀ .column. Thatāll create a die like this:
Now, we need to align the second dot to the center in a vertical direction. For that, we can apply justify-content as center to the column.
We learn about finding Number of SecondsĀ , Number of MinutesĀ , Number of hoursĀ , Number of daysĀ , Number of weeksĀ , Number of monthsĀ , Number of years between two dates.
Letās create two dates
let d1 = Date.now();
let d2 = new Date(2019,5,22).getTime(); //Jun 22 2019 in millisecond
console.log(d1); //1573527098946
console.log(d2); //1561141800000
Number of Seconds between twoĀ dates.
1 second = 1000 milliseconds
Now we are having two date d1 and d2 in milliseconds. To convert milliseconds into secondsĀ ,we can divide the difference between two dates in milliseconds by 1000Ā .
function secondsDiff(d1, d2) {
let millisecondDiff = d2 - d1;
let secDiff = Math.floor( ( d2 - d1) / 1000 );
return secDiff;
}
Number of Minutes between twoĀ dates.
1 minutes = 60 seconds
Now we have method to find the number of seconds between two datesĀ , so we can find seconds difference, then divide that by 60 will give us the number of minutes between two dates.
function minutesDiff(d1, d2) {
let seconds = secondsDiff(d1, d2);
let minutesDiff = Math.floor( seconds / 60 );
return minutesDiff;
}
Number of Hours between twoĀ dates.
1 hour = 60 minutes
Now we have method to find the number of minutes between two datesĀ , so we can find minutes difference, then divide that by 60 will give us the number of hours between two datesĀ .
function hoursDiff(d1, d2) {
let minutes = minutesDiff(d1, d2);
let hoursDiff = Math.floor( minutes/ 60 );
return hoursDiff;
}
Number of Days between twoĀ dates.
1 day = 24 hours
Now we have method to find the number of hours between two datesĀ , so we can find difference, then divide that by 24 will give us the number of days between two dates.
function daysDiff(d1, d2) {
let hours = hoursDiff(d1, d2);
let daysDiff = Math.floor( hours / 24 );
return daysDiff;
}
Number of Weeks between twoĀ dates.
1 week = 7 days
Now we have method to find the number of days between two datesĀ , so we can find difference, then divide that by 7 will give us the number of weeks between two dates.
function weeksDiff(d1, d2) {
let days = daysDiff(d1, d2);
let weeksDiff = Math.floor( days/ 7 );
return weeksDiff;
}
Number of Years between twoĀ dates.
To find number of years between two dates we have in-built method getFullYearĀ , Subtract the date2 year with date1 year, we will get yearsDiffĀ .
function yearsDiff(d1, d2) {
let date1 = new Date(d1);
let date2 = new Date(d2);
let yearsDiff = date2.getFullYear() - date1.getFullYear();
return yearsDiff;
}
Number of Months between twoĀ dates.
1 month != 30 days
Number of days in month is not same in all months , so we need to do it differently
StepsĀ :
First we need to find number of years between two dates.
Multiply number of years between two dates by 12(because for each year 12 months)
Subtract the month number(June ā 5) of second date with the month number of first date
Finding number of months between two dates
function monthsDiff(d1, d2) {
let date1 = new Date(d1);
let date2 = new Date(d2);
let years = yearsDiff(d1, d2);
let months =(years * 12) + (date2.getMonth() - date1.getMonth()) ;
return months;
}
Thanks for Reading šĀ . Hope you like this. If you found any typo or mistake send me a private note š thanks š šĀ .
Learn how the Linear search Algorithm works and how to implement itĀ .
Linear search is a Searching algorithm, which is used to check if an element is present in an array or listĀ . It is also called Sequential search.
A linear search sequentially search for the target element in the array. If it finds the element in the array it stop searching and returns successfulĀ . If it reaches the end of the array, then it returns element not found.
Algorithm
Traverse the array using a for loop (any looping technique).
In every iteration, compare the target value with the current value of the array.
If the values match, return the current index of the array.
If the values do not match, move on to the next array element.
3. If no match is found, return element not found.
Whenever we are in situation of writing multiple if/else statement for a particular test case, then the multiple if/else statement can be replaced by switch statement.
SyntaxĀ :
switch(expression_or_value) {
case expression_or_value : operation1 [break];
case expression_or_value : operation2 [break];
...
default : default operation [break]; }
// break is optional
A switch statement first evaluates its input expression.
It then checks whether the first case expression evaluates to the same value as the result of the input expression, using strict equals (===).
If the case is matched then, the code associated with the case is executed until it finds the break keyword, or also the return keyword inside functions.
If the break or return is not added to the case, then the switch statement will continue and execute the code below the match. It will continue to run until it finds a break, return, or reaches the end of the statement.
If no matching case is found then the program looks for a default clause and executes the code there.
If a default clause is not found, then it reaches end of the switch expression and does nothing.
Example:
function getCost(item) {
let cost ;
switch(item) {
case 'š': cost = '10$'; break;
case 'š' : cost = '20$';
case 'š' : cost = '30$'; break;
default : cost = "Item not in stock";
}
return cost; }
Letās execute the function and test it
getCost('š'); // 10$
getCost('š'); // 30$
getCost('apple'); // Item not in stock
getCost(āšā)ā matches the first case and executes the cost = 10$ and executes the break statement, which ends the switch statement.
getCost(āšā) ā matches the second case and executes the cost = 20$. There is no break, so the code below it is executed, and the value of cost starts at 20$ but continues to run and becomes 30$Ā .
getCost(āappleā) ā no matching case, so it executes the default case. For the last case, there is no need for the break statement because there will be no more case below itĀ .
Cases where we can skip break statement
If we want to execute same operation for two or more conditions, then we can make use of skipping break statement.
function isVowel(input) {
let isVowel = false;
switch(input) {
case 'a': case 'e': case 'i': case 'o': case 'u': isVowel = true;
}
return isVowel;
}
The order in which the cases are placed is not considered.
We can also place the default case anywhere inside the statement.
function getCost(item) {
let cost = `The cost of ${item} is `;
switch(item) {
default : cost = "Item not in stock"; break;
case 'š'; cost = '10$'; break;
case 'š' : cost = '20$':
case 'š' : cost = '30$'; break;
} return cost; }
But donāt forget to add a break statement to the end of default case if it is not placed at the end of all cases.
We can also add block to eachĀ case
function getMenu(option) {
switch(option) {
case 'veg' : { console.log('š','š','š','š', 'š'); break; }
We have some in-built methods to add at elements at the beginning and end of the array.
push(value) ā Add an element to the end of the array.
unshift(value) ā Add an element to the beginning of an array.
To add an element to the specific index there is no method available in Array object. But we can use already available splice method in Array object to achieve this.
An array starts from index 0Ā ,So if we want to add an element as first element of the arrayĀ , then the index of the element is 0Ā .If we want to add an element to nth positionĀ , then the index is (n-1) th index.
MDN :
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements, in the original array(which means the source array is modified)
splice()method takes three argument
start ā The index at which to start changing the array.
deleteCount(optional) ā An integer indicating the number of elements in the array to remove from start.
(elem1, elem2Ā ā¦) ā The elements to add to the array, beginning from start. If you do not specify any elements, splice() will only remove elements from the array.
In order to insert an element to the specific indexĀ , we need to provide arguments as
start ā index where to insert the element
deleteCount ā 0 (because we donāt need to delete element)
elem ā elements to insert
Letās Write the function
function insertAt(array, index, ...elementsArray) {
array.splice(index, 0, ...elements);
}
Now Letās call the function
var num = [1,2,3,6,7,8];
/* arguments * 1. source array - num * 2. index to insert - 3 * 3. remaining are elements to insert */
Values in arrays are desctructured based on their index. The variable can be named anything you want. The variable name associated with the index is how it is assigned.
Tips: With array destructing we can easily swap values
var a = 10,b = 20;
[b, a] = [a, b]
console.log(a, b); 20, 10
Object Destructing
We can extract data from properties of the object using object destructing. Here the name of the variable is matched with the property of the object and the corresponding property value is retrieved from the object and assigned to the variable.
var user = {name : "Ram", age : 20};
var {name, age} = user;
console.log(name, age); // "Ram", 20
Example 2:
var {name, age} = {name: "Ram", age : 20};
console.log(name, age); // "Ram", 20
If the variable name doesnāt match the property of the object, then the value of unmatched variable will be undefined.
var {name, age, salary} = {name: "Ram", age : 20};
We can’t do like {name, age} = user; because “{” is the first tokenĀ , so JavaScript thinks it is a start of blockĀ .
To solve this
({name, age} = user);
Assigning to new variable names
var user = {name : "Ram"};
var {name: userName} = user;
userName; // "Ram"
The above code takes name property from user and create a new variable with name userName and assign the value to userName variable.
Tip: We can use new variable name when the property of the object is invalid identifier name
var user = {"user-name" : "Mike"};
var {"user-name": userName} = user;
userName; //Mike
Assigning Default value
The default value can be assigned to a variable if the property is not present in the object.
var user1 = {name : "Mike", nickName : "mic"};
var {name1, nickName1="Noob Master"} = user1;
console.log(nickName1); // "mic"
//If the property not present
var user2 = {name : "Ram"};
var {name2, nickName2="Noob Master"} = user2;
console.log(nickName2); //"Noob Master"
Using both default values and new variable names
var user = {};
var { name: userName = "Default Name" } = user;
console.log(userName); // "Default Name"
Using Object Destructing as function arguments
Without destructing
function logUser(user) { var name = user.name; var age = user.age; console.log(name, age); }
var user = {name : "Mike", age : 20};
logUser(user); // "Mike", 20
The above code can be simplified to
function logUser( {name, age} ) { console.log(name, age); }
var user = {name : "Mike", age : 20};
logUser(user); // "Mike", 20
Using default value and new variable name in function argument destructing
function logUser( {name:userName, age: userAge = 30} ) {
console.log(userName, userAge);
}
var user = {name : "Mike"};
logUser(user); // "Mike" , 30
The above method logUser will throw an error if we call the method without any argument. If we donāt pass any argument, it tries to destructure undefined so it throws error. To resolve this:
function logUser({name: Name="Jack", age: Age = 30} = {}) {
Array elements are accessed using an index. The index starts from 0Ā . So if we want to access the first element, then we need to access using index 0.
numbers[0] // 1
numbers[3] // 4
numbers[9] // undefined
Find the length of theĀ array
numbers.length
Get the last element of theĀ array
let len = numbers.length;
let index = len - 1;
let lastElement = numbers[index]
Adding an element to the end of anĀ array
numbers.push(6);
numbers; // [1,2,3,4,5,6]
Adding element to the beginning of anĀ array
numbers.unshift(0);
numbers; // [0,1,2,3,4,5,6]
Deleting the last element of anĀ array
numbers.pop()
Delete the first element of theĀ array
numbers.shift()
Delete an element at specificĀ index
let numbers = [1,2,3,4,5];
let index = 2;
numbers.splice(index,1);
numbers; [1,2,4,5]
Adding an element at a specificĀ index
let numbers = [1,2,5];
let index = 2;
let elements = [3,4]
numbers.splice(index,0, ...elements);
numbers; [1, 2, 3, 4, 5]
Updating elements
var numbers = [1,2,2,4,5]
numbers[2] = 3;
numbers; // [1,2,3,4,5]
Find if an element is present in anĀ array
var numbers = [1,2,3,4,5]
numbers.includes(1);// true
numbers.includes(10);// false
Find the index of theĀ element
var numbers = [1,2,3,4,5]
numbers.indexOf(1); // 0
numbers.indexOf(10); // -1(if element not present )
Iterating over anĀ array
var numbers = [1,2,3,4,5]
for(let i = 0; i < numbers.length; i++) { console.log(numbers[i]); }
// example 1
numbers.forEach(elem => console.log(elem));
Reverse anĀ array
var numbers = [1,2,3,4,5]
numbers.reverse(); // [5, 4, 3, 2, 1]
Filter arrayĀ elements
var numbers = [1,2,3,4,5];
numbers.filter((elem) => elem > 3);// [4,5]
Mapping all elements with function and create a newĀ array
var numbers = [1,2,3,4,5];
var doubledNum = numbers.map(item => item *2 );
doubledNum; // [2,4,6,8,10]
Sorting anĀ array
let num= [1, 2, 3, 4, 5, 6];
// sort in descending order let descOrder = num.sort( (a, b) => a > b ? -1 : 1 );