diff --git a/README.md b/README.md index 9ea5671..113a967 100644 --- a/README.md +++ b/README.md @@ -18,15 +18,13 @@ function sum(x, y) { }; } } -``` - -Output -```js console.log(sum(2,3)); // Outputs 5 console.log(sum(2)(3)); // Outputs 5 ``` +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-cp-1-ypmjhl?file=/src/index.js)** +
↥ back to top
@@ -36,69 +34,41 @@ console.log(sum(2)(3)); // Outputs 5 ```html - - - Show File Data - - - -
- - -
- + console.log("File Name: " + file.name); + console.log("File Size: " + file.size + " bytes"); + console.log("File Extension: " + extension); + } + + + + +
+ + +
+ + + + +File Name: pic.jpg +File Size: 1159168 bytes +File Extension: jpg ``` +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-cp-file-upload-fj17kh?file=/index.html)** +
↥ back to top
@@ -115,34 +85,20 @@ console.log(sum(2)(3)); // Outputs 5 var captcha; function generateCaptcha() { - var a = Math.floor(Math.random() * 10); - var b = Math.floor(Math.random() * 10); - var c = Math.floor(Math.random() * 10); - var d = Math.floor(Math.random() * 10); - - captcha = a.toString() + b.toString() + c.toString() + d.toString(); + captcha = Math.floor(Math.random() * 1000000); document.getElementById("captcha").value = captcha; } - - function check() { - var input = document.getElementById("inputText").value; - - if (input == captcha) { - alert("Valid Captcha"); - } else { - alert("Invalid Captcha"); - } - } +

-

- ``` +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-cp-captcha-mzyi2n?file=/index.html)** +
↥ back to top
@@ -155,107 +111,74 @@ console.log(sum(2)(3)); // Outputs 5 Stopwatch Example + -
-

Simple stopwatch made in JavaScript

- - - -
-

- 0 : 00 : - 000 -

-

- In this example Date() methods co-operate with timing function - setInterval(). -

+

Time: 00:00:00



+ + + ``` +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-cp-stopwatch-j6in1i?file=/index.html)** +
↥ back to top
@@ -270,9 +193,13 @@ function reverseString(str) { } return stringRev; } -alert(reverseString("Pradeep")); // Output: peedarP +console.log(reverseString("Hello")); + +// Output: olleH ``` +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-cp-reversestring-sgm1ip?file=/src/index.js)** +
↥ back to top
@@ -283,19 +210,39 @@ alert(reverseString("Pradeep")); // Output: peedarP function isEmpty(obj) { return Object.keys(obj).length === 0; } + +const obj = {}; +console.log(isEmpty(obj)); // true ``` +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-cp-isempty-b7n04b?file=/src/index.js)** + +
+ ↥ back to top +
+ ## Q. ***JavaScript Regular Expression to validate Email*** ```javascript -var pattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/; +function validateEmail(email) { + const re = /\S+@\S+\.\S+/; + return re.test(email); +} + +console.log(validateEmail("pradeep.vwa@gmail.com")); // true ``` +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-cp-validateemail-wfopym?file=/src/index.js)** + +
+ ↥ back to top +
+ ## Q. ***Use RegEx to test password strength in JavaScript?*** ```javascript -var newPassword = "Pq5*@a{J"; -var regularExpression = new RegExp( +let newPassword = "Pq5*@a{J"; +const regularExpression = new RegExp( "^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*])(?=.{8,})" ); @@ -303,7 +250,12 @@ if (!regularExpression.test(newPassword)) { alert( "Password should contain atleast one number and one special character !" ); +} else { + console.log("PASS"); } + +// Output +PASS ``` | RegEx | Description | @@ -315,6 +267,8 @@ if (!regularExpression.test(newPassword)) { | (?=.[!@#\$%\^&]) | The string must contain at least one special character, but we are escaping reserved RegEx characters to avoid conflict | | (?=.{8,}) | The string must be eight characters or longer | +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-cp-password-strength-cxl8xy)** +
↥ back to top
@@ -8066,23 +8020,271 @@ c.retrieve(); // => The counter is currently at: 14 ## Q. ***How to divide an array in multiple equal parts in JS?*** ```js -function splitArrayIntoChunksOfLen(arr, len) { - let chunks = [], - i = 0, - n = arr.length; +const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; +let lenth = 3; + +function split(len) { + while (arr.length > 0) { + console.log(arr.splice(0, len)); + } +} +split(lenth); + +// Output +(3) [1, 2, 3] +(3) [4, 5, 6] +(3) [7, 8, 9] +(1) [10] +``` + +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/split-array-5od3rz)** + +
+ ↥ back to top +
+ +## Q. ***Write a random integers function to print integers with in a range?*** + +**Example:** + +```js +/** + * function to return a random number + * between min and max range + * + * */ +function randomInteger(min, max) { + return Math.floor(Math.random() * (max - min + 1) ) + min; +} +randomInteger(1, 100); // returns a random integer from 1 to 100 +``` + +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-random-integers-yd1cy8?file=/src/index.js)** + +
+ ↥ back to top +
+ +## Q. ***How to convert Decimal to Binary in JavaScript?*** + +**Example 01:** Convert Decimal to Binary + +```js +function DecimalToBinary(number) { + let bin = 0; + let rem, + i = 1; + while (number !== 0) { + rem = number % 2; + number = parseInt(number / 2); + bin = bin + rem * i; + i = i * 10; + } + console.log(`Binary: ${bin}`); +} + +DecimalToBinary(10); +``` + +**Example 02:** Convert Decimal to Binary Using `toString()` + +```js +let val = 10; + +console.log(val.toString(2)); // 1010 ==> Binary Conversion +console.log(val.toString(8)); // 12 ==> Octal Conversion +console.log(val.toString(16)); // A ==> Hexadecimal Conversion +``` - while (i < n) { - chunks.push(arr.slice(i, (i += len))); +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-decimal-to-binary-uhyi8t?file=/src/index.js)** + +
+ ↥ back to top +
+ +## Q. ***How do you make first letter of the string in an uppercase?*** + +You can create a function which uses chain of string methods such as charAt, toUpperCase and slice methods to generate a string with first letter in uppercase. + +```js +function capitalizeFirstLetter(string) { + let arr = string.split(" "); + for (var i = 0; i < arr.length; i++) { + arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1); + } + return arr.join(" "); +} + +console.log(capitalizeFirstLetter("hello world")); // Hello World +``` + +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-capitalizefirstletter-dpjhky?file=/src/index.js)** + +
+ ↥ back to top +
+ +## Q. ***Write a function which will test string as a literal and as an object?*** + +The `typeof` operator can be use to test string literal and `instanceof` operator to test String object. + +```js +function check(str) { + if (str instanceof String) { + return "It is an object of string"; + } else { + if (typeof str === "string") { + return "It is a string literal"; + } else { + return "another type"; + } + } +} + +var ltrlStr = "Hi I am string literal"; +var objStr = new String("Hi I am string object"); + +console.log(check(ltrlStr)); // It is a string literal +console.log(check(objStr)); // It is an object of string +``` + +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-literal-vs-object-978dqw?file=/src/index.js)** + +
+ ↥ back to top +
+ +## Q. ***How do you reversing an array?*** + +You can use reverse() method is used reverse the elements in an array. This method is useful to sort an array in descending order. Let us see the usage of reverse() method in an example, + +```js +let numbers = [1, 2, 5, 3, 4]; +numbers.sort((a, b) => b - a); +numbers.reverse(); +console.log(numbers); // [1, 2, 3, 4 ,5] +``` + +
+ ↥ back to top +
+ +## Q. ***How do you find min and max value in an array?*** + +You can use `Math.min` and `Math.max` methods on array variable to find the minimum and maximum elements with in an array. +Let us create two functions to find the min and max value with in an array, + +```js +var marks = [50, 20, 70, 60, 45, 30]; +function findMin(arr) { + return Math.min.apply(null, arr); +} +function findMax(arr) { + return Math.max.apply(null, arr); +} + +console.log(findMin(marks)); +console.log(findMax(marks)); +``` + +
+ ↥ back to top +
+ +## Q. ***How do you find min and max values without Math functions?*** + +You can write functions which loops through an array comparing each value with the lowest value or highest value to find the min and max values. Let us create those functions to find min an max values, + +```js +var marks = [50, 20, 70, 60, 45, 30]; +function findMin(arr) { + var length = arr.length + var min = Infinity; + while (length--) { + if (arr[length] < min) { + min = arr[length]; + } + } + return min; +} + +function findMax(arr) { + var length = arr.length + var max = -Infinity; + while (length--) { + if (arr[length] > max) { + max = arr[length]; + } + } + return max; +} + +console.log(findMin(marks)); +console.log(findMax(marks)); +``` + +
+ ↥ back to top +
+ +## Q. ***Write code for merge two JavaScript Object dynamically?*** + +Let say you have two objects + +```js +const person = { + name: "Tanvi", + age: 28 +}; + +const address = { + addressLine1: "Some Location x", + addressLine2: "Some Location y", + city: "Bangalore" +}; +``` + +Write merge function which will take two object and add all the own property of second object into first object. + +```js +merge(person , address); + +/* Now person should have 5 properties +name , age , addressLine1 , addressLine2 , city */ +``` + +**Method 1: Using ES6, Object.assign method:** + +```js +const merge = (toObj, fromObj) => Object.assign(toObj, fromObj); + +console.log(merge(person, address)); +// {name: "Tanvi", age: 28, addressLine1: "Some Location x", addressLine2: "Some Location y", city: "Bangalore"} +``` + +**Method 2: Without using built-in function:** + +```js +function mergeObject(toObj, fromObj) { + // Make sure both of the parameter is an object + if (typeof toObj === "object" && typeof fromObj === "object") { + for (var pro in fromObj) { + // Assign only own properties not inherited properties + if (fromObj.hasOwnProperty(pro)) { + // Assign property and value + toObj[pro] = fromObj[pro]; + } + } + } else { + throw "Merge function can apply only on object"; } - return chunks; } -let alphabet = ["a", "b", "c", "d", "e", "f"]; -let alphabetPairs = splitArrayIntoChunksOfLen(alphabet, 2); //split into chunks of two -console.log(alphabetPairs); +console.log(mergeObject(person, address)); +// {name: "Tanvi", age: 28, addressLine1: "Some Location x", addressLine2: "Some Location y", city: "Bangalore"} ``` -**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/splitarrayintochunksoflen-5od3rz?file=/src/index.js:0-345)** +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-shallow-vs-deep-copy-ik5b7h?file=/src/index.js)**
↥ back to top