├── Arrays - Map, Filter, Reduce ├── OutputQuestions.js ├── Reduce.js └── index.js ├── Call, Bind & Apply ├── OutputQuestions.js └── index.js ├── Closures └── OutputQuestions.js ├── Currying └── OutputQuestions.js ├── Debouncing_&_Throttling └── index.js ├── Event Propagation └── index.js ├── Objects └── OutputQuestions.js ├── Promises ├── OutputQuestions.js ├── Polyfills │ └── 1. PromiseAll.js └── index.js ├── PrototypalInheritance └── index.js ├── README.md ├── Testing └── UnitTesting │ └── Jest │ ├── Readme.md │ ├── index.js │ └── index.test.js ├── VanillaUI └── 1. CenterDiv │ ├── Readme.md │ ├── index.css │ ├── index.html │ └── index.js └── this_keyword └── index.js /Arrays - Map, Filter, Reduce/OutputQuestions.js: -------------------------------------------------------------------------------- 1 | // Q1 - Return Name of student in capital 2 | const names = students.map((student) => { 3 | return student.name.toUpperCase(); 4 | }) 5 | console.log(names); 6 | // Output - [ 'SAM', 'MOHIT', 'SAPNA', 'TIM' ] 7 | 8 | 9 | // Q2 - Return students with more than 60 marks 10 | const filteredStudents = students.filter((student) => { 11 | return student.marks > 60 12 | }) 13 | console.log(filteredStudents); 14 | // Output - [ 15 | // { name: 'Sam', rollNumber: 17, marks: 80 }, 16 | // { name: 'Mohit', rollNumber: 35, marks: 69 } 17 | // ] 18 | 19 | 20 | // Q3 - Return students with more than 60 marks & roll number less than 20 21 | const filteredStudents = students.filter((student) => { 22 | return student.marks > 60 && student.rollNumber < 20; 23 | }) 24 | console.log(filteredStudents); 25 | // Output - [ { name: 'Sam', rollNumber: 17, marks: 80 } ] 26 | 27 | 28 | // Q4 - Return total marks of all students 29 | const totalMarks = students.reduce((acc, curr) => { 30 | return acc + curr.marks; 31 | }, 0) 32 | console.log(totalMarks); 33 | // Output - 239 34 | 35 | 36 | // Q5 - Return student names with more than 60 marks 37 | const filteredStudents = students.filter((student) => { 38 | return student.marks > 60 39 | }).map((student) => { 40 | return student.name 41 | }) 42 | console.log(filteredStudents); 43 | // Output - [ 'Sam', 'Mohit' ] 44 | 45 | 46 | // Q6 - Return total marks for students with marks > 60 after 20 marks have been added to those who scored < 60 47 | const totalMarks = students.map((student) => { 48 | if (student.marks < 60) { 49 | student.marks += 20; 50 | } 51 | return student; 52 | }).filter((student) => { 53 | return student.marks > 60 54 | }).reduce((acc, current) => { 55 | return acc + current.marks; 56 | }, 0) 57 | 58 | console.log(totalMarks); 59 | // Output - 224 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /Arrays - Map, Filter, Reduce/Reduce.js: -------------------------------------------------------------------------------- 1 | 2 | // Reduce can be used in many ways, 3 | // Aggregation 4 | const arr = [1, 2, 3, 4]; 5 | 6 | let sum = arr.reduce((pv, cv) => { 7 | const newValue = pv + cv; 8 | return newValue; 9 | }, 0) 10 | 11 | console.log(sum); 12 | 13 | 14 | // Segregation - Can group elements together based on certain requirements 15 | const arr = ['a', 'b', 'c', '*', 'd', '$']; 16 | 17 | 18 | const isSpecial = (value) => { 19 | if (['$', '#', "*"].includes(value)) return "special"; 20 | else return "normal" 21 | } 22 | 23 | const segregate = arr.reduce((pv, cv) => { 24 | const val = isSpecial(cv); 25 | if (!pv[val]) { 26 | pv[val] = []; 27 | } 28 | 29 | pv[val].push(cv); 30 | return pv; 31 | 32 | }, {}); 33 | 34 | console.log(segregate); 35 | 36 | 37 | // Can also be used to run things in sequence 38 | const upperCase = (str) => { 39 | return str.toUpperCase(); 40 | } 41 | 42 | const reverse = (str) => { 43 | return str.split('').reverse().join(''); 44 | } 45 | 46 | const append = (str) => { 47 | return "Hello + " + str; 48 | } 49 | 50 | const arr = [append, reverse, upperCase]; 51 | 52 | const fV = arr.reduce((pv, cv) => { 53 | const newValue = cv(pv); 54 | console.log(`${cv}, ${newValue}`) 55 | return newValue 56 | }, "sam"); 57 | 58 | 59 | 60 | // same with promises 61 | const asyncTask = (time) => { 62 | return new Promise((res, rej) => { 63 | setTimeout(() => { 64 | res(`completed in ${time}`) 65 | }, 100 * time); 66 | }) 67 | } 68 | 69 | const promises = [ 70 | asyncTask(7), 71 | asyncTask(3), 72 | asyncTask(1), 73 | ] 74 | 75 | const resPromises = (promises) => { 76 | promises.reduce((acc, curr) => { 77 | return acc.then(() => { 78 | return curr.then((val) => console.log(val)) 79 | }) 80 | }, Promise.resolve()) 81 | } 82 | 83 | resPromises(promises); 84 | -------------------------------------------------------------------------------- /Arrays - Map, Filter, Reduce/index.js: -------------------------------------------------------------------------------- 1 | /// Map /// 2 | const arr = [1, 8, 9, 4]; 3 | 4 | // Map - Inbuilt 5 | const newArr = arr.map((element, elementIndex, array) => { 6 | return element * 2; 7 | }) 8 | 9 | // Map - Polyfill 10 | Array.prototype.myMap = function (cbFunction) { 11 | // since map returns an array 12 | let arr = []; 13 | for (let i = 0; i < this.length; i++) { 14 | arr.push(cbFunction(this[i], i, this)); 15 | } 16 | 17 | return arr; 18 | } 19 | 20 | const newArr = arr.myMap((element, elementIndex, array) => { 21 | return element * 2; 22 | }) 23 | 24 | //output = [ 2, 16, 18, 8 ] 25 | 26 | 27 | /// Filter /// 28 | const arr = [1, 8, 9, 4]; 29 | 30 | // Fitler - Inbuilt 31 | const newArr = arr.filter((element, elementIndex, array) => { 32 | return element > 2; 33 | }) 34 | 35 | // Filter - Polyfill 36 | Array.prototype.myFilter = function (cbFunction) { 37 | let arr = []; 38 | for (let i = 0; i < this.length; i++) { 39 | if (cbFunction(this[i], i, this)) { 40 | arr.push(this[i]); 41 | } 42 | } 43 | return arr; 44 | } 45 | 46 | const newArr = arr.myFilter((element, elementIndex, array) => { 47 | return element > 2; 48 | }) 49 | 50 | // output = [ 8, 9, 4] 51 | 52 | 53 | 54 | /// Reduce /// 55 | const arr = [1, 8, 9, 4]; 56 | 57 | // Reduce - Inbuilt 58 | const sum = arr.reduce((acc, curr, currIndex, array) => { 59 | return acc + curr; 60 | }, 0); 61 | 62 | // Reduce - Polyfill 63 | Array.prototype.myReduce = function (cbFunction, initialValue) { 64 | var accumulator = initialValue; 65 | for (let i = 0; i < this.length; i++) { 66 | accumulator = accumulator ? cbFunction(accumulator, this[i], i, this) : this[i]; 67 | 68 | } 69 | 70 | return accumulator; 71 | } 72 | 73 | 74 | const sum = arr.myReduce((acc, curr, currIndex, array) => { 75 | return acc + curr; 76 | }, 0); 77 | 78 | // output = 22 79 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /Call, Bind & Apply/OutputQuestions.js: -------------------------------------------------------------------------------- 1 | // Q1.Output 2 | let person = { 3 | name: 'sam' 4 | } 5 | 6 | function sayHello(age) { 7 | return "hello " + this.name + " whose age is " + age; 8 | } 9 | 10 | 11 | console.log(sayHello.call(person, 33)); // hello sam whose age is 33 12 | console.log(sayHello.bind(person, 33)); // return function 13 | 14 | 15 | // Q2. Output 16 | const age = 10; 17 | 18 | var person = { 19 | name: 'sam', 20 | age: 23, 21 | getAge: function () { 22 | return this.age; 23 | } 24 | } 25 | 26 | var p2 = { age: 24 }; 27 | 28 | console.log(person.getAge.call(p2)); // 24 29 | 30 | 31 | // Q3. Output 32 | var name = 'sam'; 33 | 34 | setTimeout(() => { 35 | const name = "mes"; 36 | 37 | const data = { 38 | name: "mike", 39 | getName() { 40 | return this.name 41 | } 42 | 43 | 44 | }; 45 | 46 | console.log(data.getName()); // mike 47 | console.log(data.getName.call(this)); // sam - as this points to the context the func is called in 48 | }) 49 | 50 | 51 | // Q3. Output 52 | const animals = [ 53 | { 54 | name: 'tiger', 55 | age: 13, 56 | }, 57 | { 58 | name: 'lion', 59 | age: 15, 60 | } 61 | ] 62 | 63 | function printAnimals(i) { 64 | this.print = function () { 65 | console.log("#" + i + " " + this.name + " with " + this.age); 66 | } 67 | this.print(); 68 | } 69 | 70 | printAnimals(); 71 | for (let i = 0; i < animals.length; i++) { 72 | printAnimals.call(animals[i], i) // #0 tiger with 13, #1 lion with 15 73 | 74 | } 75 | 76 | // Q4. Append two arrays 77 | Ans: 78 | const arr1 = [1, 2, 3]; 79 | const arr2 = [4, 5, 7]; 80 | 81 | arr1.push.apply(arr1, arr2); 82 | 83 | console.log(arr1); // [ 1, 2, 3, 4, 5, 7 ] 84 | 85 | // Q5. Max & min 86 | Ans: 87 | const arr1 = [1, 2, 3, 4, 5, 7]; 88 | 89 | console.log(Math.max.apply(null, arr1)); // 7 90 | console.log(Math.min.apply(null, arr1)); // 1 91 | 92 | 93 | // Q5. Bound Output 94 | console.log(this); 95 | } 96 | 97 | let user = { 98 | g: f.bind(null), 99 | } 100 | 101 | user.g(); // refers to window obj 102 | 103 | 104 | // Q6. Output 105 | function f() { 106 | console.log(this.name); 107 | } 108 | 109 | f = f.bind({ name: "sam" }).bind({ name: "mes" }); 110 | 111 | f(); // sam - as bind is fixed, 112 | -------------------------------------------------------------------------------- /Call, Bind & Apply/index.js: -------------------------------------------------------------------------------- 1 | // Usage Inbuilt + Polyfill 2 | let obj = { 3 | name: 'sam' 4 | } 5 | 6 | function sayHello(age) { 7 | return "hello " + this.name + " whose age is " + age; 8 | } 9 | // Call 10 | console.log(sayHello.call(obj, 33)); // hello sam whose age is 33 11 | 12 | 13 | // Call Polyfill 14 | let obj = { 15 | name: 'sam', 16 | } 17 | function sayHello(age) { 18 | console.log("hello " + this.name + " whose age is " + age); 19 | } 20 | Function.prototype.customCall = function (context, ...args) { 21 | if (typeof this !== "function") throw new Error("not a function"); 22 | context.fnRef = this; 23 | context.fnRef(...args); 24 | 25 | } 26 | 27 | // Apply 28 | console.log(sayHello.apply(obj, [33])); // hello sam whose age is 33 29 | 30 | 31 | // Apply Polyfill 32 | Function.prototype.customApply = function (context = {}, args = []) { 33 | if (typeof this !== "function") throw new Error("not a function"); 34 | if (!Array.isArray(args)) throw new Error("Provide array"); 35 | context.fnRef = this; 36 | // spreading the contents of args array here 37 | context.fnRef(...args); 38 | 39 | } 40 | sayHello.customApply(obj, [33]); 41 | 42 | 43 | // Bind 44 | const binded = sayHello.bind(obj); 45 | 46 | console.log(binded(33)); // hello sam whose age is 33 47 | console.log(binded(44)); // hello sam whose age is 44 48 | 49 | 50 | 51 | // Bind Polyfill 52 | Function.prototype.customBind = function (context = {}, ...args) { 53 | if (typeof this !== "function") throw new Error("not a function"); 54 | 55 | context.fnRef = this; 56 | return function (...newArgs) { 57 | return context.fnRef(...args, ...newArgs); 58 | } 59 | 60 | } 61 | 62 | const bindFunc = sayHello.customBind(obj); 63 | bindFunc(33); 64 | -------------------------------------------------------------------------------- /Closures/OutputQuestions.js: -------------------------------------------------------------------------------- 1 | // Q1. Guess output 2 | let count = 0; 3 | (function printCount(){ 4 | if (count === 0){ 5 | let count = 1; 6 | console.log(count); 7 | } 8 | console.log(count); 9 | })() 10 | // Output - 1 11 | // 0 12 | 13 | 14 | // Q2. Write a function for following 15 | // var multiply6 = createBase(6); 16 | // multiply6(10);// returns 60 17 | // multiply6(21);// returns 126 18 | Ans: const createBase = (a) => { 19 | return (b) => { 20 | console.log(a * b); 21 | } 22 | } 23 | 24 | var multiply6 = createBase(6); 25 | multiply6(21); 26 | multiply6(10); 27 | // Output - 126 28 | //60 29 | 30 | 31 | // Q3 - Optimize time take, 32 | function find(index) { 33 | let a = []; 34 | for (let i = 0; i < 1000000; i++) { a[i]= i*i } 35 | 36 | console.log(a[index]) 37 | } 38 | Ans: 39 | const find = (index) => { 40 | let arr = []; 41 | for (let i= 0; i < 1000000; i++){ 42 | arr[i] = i * i; 43 | } 44 | return (index) => { 45 | console.log(arr[index]); 46 | } 47 | } 48 | 49 | // Q4 - SetTimout optimization 50 | function a(){ 51 | for (var i = 0; i < 3; i++){ 52 | setTimeout(() => { 53 | console.log(i); 54 | }, i * 1000) 55 | } 56 | } 57 | 58 | a(); 59 | // gives 3, 3, 3 60 | Ans: 61 | function a(){ 62 | for (var i = 0; i < 3; i++){ 63 | const printOutput = (i) => { 64 | setTimeout(() => { 65 | console.log(i); 66 | }, i * 1000); 67 | } 68 | printOutput(i); 69 | } 70 | } 71 | a(); 72 | // gives 0, 1, 2 73 | 74 | 75 | // Q5. Implement private counter 76 | Ans: 77 | const counter = () => { 78 | let _counter = 0; 79 | 80 | const add = (num) => { 81 | _counter += num 82 | } 83 | 84 | const get = () => { 85 | return _counter; 86 | } 87 | 88 | return {add, get}; 89 | } 90 | 91 | const getCounter = counter(); 92 | getCounter.add(4); 93 | getCounter.add(41); 94 | console.log(getCounter.get()); // gives 45 95 | 96 | 97 | // Q6: Module Pattern 98 | var Module = (function(){ 99 | const private = (i) => { 100 | console.log("private:" + i); 101 | 102 | } 103 | 104 | return { 105 | public: (i) => { 106 | return private(i); 107 | } 108 | } 109 | })() 110 | 111 | Module.public(9); // gives private: 9 112 | Module.private(9); // gives error 113 | 114 | // Q7: Make it run once 115 | Ans Approach1: let message; 116 | const helloSam = () => { 117 | let count = 0; 118 | return () => { 119 | if (count > 0){ 120 | return; 121 | }else{ 122 | message = "Hello SaM;"; 123 | console.log(message); 124 | count++; 125 | } 126 | } 127 | 128 | } 129 | 130 | const heySam = helloSam(); 131 | heySam(); // gives Hello SaM; 132 | heySam(); 133 | heySam(); 134 | 135 | // More generic approach 136 | const once = function(func, context){ 137 | let ran; 138 | return function(){ 139 | if (func){ 140 | ran = func.apply(context, this); 141 | func = null; 142 | } 143 | } 144 | 145 | return ran; 146 | } 147 | 148 | const sam = once(() => console.log("Hello World")); 149 | 150 | sam(); 151 | sam(); 152 | sam(); 153 | 154 | 155 | // Q8. Implement Memoization 156 | function myMemo(func, context){ 157 | let result = {}; 158 | return function(...args){ 159 | var argsCache = JSON.stringify(args); 160 | if (!result[argsCache]){ 161 | result[argsCache] = func.call(context || this, ...args); 162 | } 163 | return result[argsCache]; 164 | } 165 | } 166 | 167 | const getProduct = (a, b) => { 168 | for (let i = 0; i <= 100000000; i++){ 169 | 170 | } 171 | return a * b; 172 | } 173 | 174 | const memoProduct = myMemo(getProduct) 175 | console.time("1st call"); 176 | console.log(memoProduct(881, 983)); 177 | console.timeEnd("1st call"); 178 | 179 | console.time("2nd call"); 180 | console.log(memoProduct(881, 983)); 181 | console.timeEnd("2nd call"); 182 | 183 | 184 | 185 | 186 | -------------------------------------------------------------------------------- /Currying/OutputQuestions.js: -------------------------------------------------------------------------------- 1 | // Q1. Turn f(a,b) to f(a)(b) 2 | Ans: 3 | const curriedExample = (a) => { 4 | return (b) => { 5 | return `${a} ${b}`; 6 | } 7 | } 8 | 9 | console.log(curriedExample(3)(4)); // 3 4 10 | 11 | 12 | // Q2. Implement sum(a)(b)(c) 13 | Ans: 14 | const sum = (a) => { 15 | return (b) => { 16 | return (c) => { 17 | return a + b + c; 18 | } 19 | } 20 | } 21 | 22 | console.log(sum(1)(3)(4)); // 8 23 | 24 | // Q3. Infinite currying sum(a)(b)..() 25 | Ans: 26 | const add = (a) => { 27 | return (b) => { 28 | if (b) return add(a + b); 29 | return a; 30 | } 31 | } 32 | 33 | console.log(add(1)(3)(4)()); 34 | 35 | // Q4. Dom example 36 | Ans: 37 | const updateElement = (classValue) => { 38 | return (content) => { 39 | return element = document.querySelector("." + classValue).innerHTML = content; 40 | } 41 | } 42 | 43 | const manipulateEle = updateElement("some0"); 44 | manipulateEle('hey'); 45 | 46 | 47 | // Q5. Implement curry 48 | Ans: 49 | const curry = (func) => { 50 | return curriedFunc = (...arguments) => { 51 | if (arguments.length >= func.length) { 52 | return func(...arguments); 53 | } else { 54 | return (...next) => { 55 | return curriedFunc(...arguments, ...next); 56 | } 57 | } 58 | } 59 | } 60 | 61 | const sum = (a, b, c) => a + b + c; 62 | console.log(sum(1, 2, 3)); // 6 63 | const totalSum = curry(sum); 64 | console.log(totalSum(1)(2)(3)); // 6 65 | -------------------------------------------------------------------------------- /Debouncing_&_Throttling/index.js: -------------------------------------------------------------------------------- 1 | // Debounce & throttle 2 | const btnValue = document.querySelector(".incrementBtn"); 3 | const incrementValue = document.querySelector(".btnIncrement"); 4 | const customValue = document.querySelector(".btnThrottled"); 5 | 6 | let normalCount = 0; 7 | let customCount = 0; 8 | 9 | 10 | 11 | // Lodash debounce 12 | const debounceCount = _.debounce(() => { 13 | customValue.innerHTML = ++customCount; 14 | 15 | }, 800); 16 | 17 | 18 | btnValue.addEventListener('click', () => { 19 | 20 | incrementValue.innerHTML = ++normalCount; 21 | debounceCount(); 22 | }) 23 | 24 | 25 | // Debounce Polyfill 26 | const customDebounce = (cb, delay) => { 27 | let timer; 28 | 29 | return function (...args) { 30 | if (timer) clearTimeout(timer); 31 | timer = setTimeout(() => { 32 | cb(...args) 33 | }, delay) 34 | } 35 | } 36 | 37 | const debounceCount = customDebounce(() => { 38 | customValue.innerHTML = ++customCount; 39 | 40 | }, 800); 41 | 42 | 43 | 44 | 45 | // Lodash throttle 46 | const throttleCount = _.throttle(() => { 47 | customValue.innerHTML = ++customCount; 48 | }, 1600); 49 | 50 | 51 | btnValue.addEventListener('click', () => { 52 | 53 | incrementValue.innerHTML = ++normalCount; 54 | throttleCount(); 55 | }) 56 | 57 | 58 | // Lodash polyfill 59 | const customThrottle = (cb, delay) => { 60 | let last = 0; 61 | 62 | return function (...args) { 63 | let now = new Date().getTime(); 64 | if (now - last < delay) return; 65 | last = now; 66 | return cb(...args); 67 | } 68 | } 69 | 70 | const throttleCount = customThrottle(() => { 71 | customValue.innerHTML = ++customCount; 72 | }, 800); 73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /Event Propagation/index.js: -------------------------------------------------------------------------------- 1 | // Event bubbling + event.target ... 2 | const some0 = document.querySelector('.some0'); 3 | const some1 = document.querySelector('.some1'); 4 | const some2 = document.querySelector('.some2'); 5 | 6 | some0.addEventListener("click", 7 | handleClick 8 | ); 9 | 10 | some1.addEventListener("click", 11 | handleClick 12 | ) 13 | 14 | some2.addEventListener("click", 15 | handleClick 16 | ) 17 | 18 | function handleClick(event) { 19 | alert(event.target.tagName + event.currentTarget.tagName + this.tagName); 20 | } 21 | 22 | // Event capturing 23 | const some0 = document.querySelector('.some0'); 24 | const some1 = document.querySelector('.some1'); 25 | const some2 = document.querySelector('.some2'); 26 | 27 | some0.addEventListener("click", () => { 28 | alert("some 0 clicked"); 29 | }, { 30 | capture: true 31 | }); 32 | 33 | some1.addEventListener("click", () => { 34 | alert("some 1 clicked"); 35 | }, { 36 | capture: true 37 | }) 38 | 39 | some2.addEventListener("click", () => { 40 | alert("some 2 clicked"); 41 | }, { 42 | capture: true 43 | }) 44 | 45 | 46 | // Event delegation 47 | const some0 = document.querySelector('.some0'); 48 | const some1 = document.querySelector('.some1'); 49 | const some2 = document.querySelector('.some2'); 50 | 51 | some0.addEventListener("click", (e) => { 52 | 53 | console.log(e.target.tagName); 54 | 55 | },); 56 | 57 | -------------------------------------------------------------------------------- /Objects/OutputQuestions.js: -------------------------------------------------------------------------------- 1 | // Q1. Guess output 2 | const a = {}; 3 | const b = { name: 'b' }; 4 | const c = { name: 'c' }; 5 | 6 | a[b] = 33; 7 | a[c] = 49; 8 | console.log(a[b]); 9 | 10 | Ans: 49; 11 | 12 | // Q2. Output 13 | console.log([..."sam"]); // ['s', 'a', 'm'] 14 | 15 | // Q3. Output 16 | let c = { name: "sam" }; 17 | let d; 18 | 19 | d = c; 20 | c.name = "mes"; 21 | console.log(d.name); // mes 22 | 23 | // Q4. output 24 | let c = { name: "sam" }; 25 | let d; 26 | 27 | d = c; 28 | c = "mes" 29 | console.log(d, c); // { name: 'sam' } mes 30 | 31 | 32 | // Q5. Output 33 | const val = { number: 10 }; 34 | 35 | const mul = (x = { ...val }) => { 36 | console.log(x.number *= 2); 37 | } 38 | 39 | mul(); // 20 40 | mul(); // 20 41 | mul(val); // 20 42 | mul(val); // 40 43 | 44 | 45 | // Q6. Output 46 | const changeRef = (person) => { 47 | person.age = 30; 48 | person = { 49 | name: 'sam', 50 | age: 50 51 | } 52 | 53 | return person; 54 | } 55 | 56 | const person1 = { 57 | name: 'mes', 58 | age: 25, 59 | } 60 | 61 | const person2 = changeRef(person1); // { name: 'mes', age: 30 } { name: 'sam', age: 50 } 62 | 63 | 64 | // Q7. Cloning objects 65 | const p1 = { 66 | name: 'sam', 67 | roll: 19 68 | } 69 | 70 | const p2 = p1; // attaches ref 71 | const p3 = Object.assign({}, p1); 72 | const p4 = JSON.parse(JSON.stringify(p1)); 73 | const p5 = { ...p1 }; 74 | 75 | p1.name = "mes"; 76 | console.log(p1, p2, p3, p4, p5); 77 | //{ name: 'mes', roll: 19 } { name: 'mes', roll: 19 } { name: 'sam', roll: 19 } { name: 'sam', roll: 19 } { name: 'sam', roll: 19 } 78 | 79 | 80 | -------------------------------------------------------------------------------- /Promises/OutputQuestions.js: -------------------------------------------------------------------------------- 1 | // Q1. Output 2 | console.log("started"); 3 | 4 | const p1 = new Promise((res, rej) => { 5 | console.log(1); 6 | res(2); 7 | console.log(3); 8 | }) 9 | 10 | p1.then((res) => { 11 | console.log(res); 12 | }) 13 | 14 | console.log("ended"); // started, 1, 3, ended, 2 15 | 16 | // Q2. Output 17 | console.log("started"); 18 | 19 | const p1 = () => { 20 | return new Promise((res, rej) => { 21 | console.log(1); 22 | res(2); 23 | console.log(3); 24 | 25 | }) 26 | } 27 | 28 | console.log("middle"); 29 | 30 | p1().then((res) => { 31 | console.log(res); 32 | }) 33 | 34 | console.log("ended"); // started, middle, 1, 3, ended, 2 35 | 36 | // Q3. Output 37 | function job() { 38 | return new Promise(function (res, rej) { 39 | rej(); 40 | }) 41 | } 42 | 43 | let p1 = job(); 44 | 45 | p1 46 | .then(function () { 47 | console.log("success1") 48 | }) 49 | .then(function () { 50 | console.log("success2") 51 | }) 52 | .then(function () { 53 | console.log("success3") 54 | }) 55 | .catch(function () { 56 | console.log("error1"); 57 | }) 58 | .then(function () { 59 | console.log("success 4"); 60 | }) // Erro1, success 4 61 | 62 | // Q4. 63 | -------------------------------------------------------------------------------- /Promises/Polyfills/1. PromiseAll.js: -------------------------------------------------------------------------------- 1 | // Promise all polyfill - 1st Approach 2 | const step1 = (v) => { 3 | return new Promise((res, rej) => { 4 | setTimeout(() => { 5 | res(v + " Sam "); 6 | }, 800); 7 | }) 8 | 9 | } 10 | 11 | 12 | const step2 = (v) => { 13 | return new Promise((res, rej) => { 14 | setTimeout(() => { 15 | res(v + " Mes "); 16 | }, 800); 17 | }) 18 | } 19 | const step3 = (v) => { 20 | return new Promise((res, rej) => { 21 | setTimeout(() => { 22 | res(v + "Kes "); 23 | }, 800); 24 | }); 25 | } 26 | 27 | 28 | Promise.customAll = (promises) => { 29 | return new Promise((resolve, reject) => { 30 | let results = []; 31 | 32 | if (!promises.length) { 33 | resolve(results); 34 | return; 35 | } 36 | 37 | let pending = promises.length; 38 | 39 | promises.forEach((p, index) => { 40 | Promise.resolve(p) 41 | .then((res) => { 42 | results[index] = res; 43 | pending--; 44 | 45 | if (pending == 0) { 46 | resolve(results); 47 | } 48 | }, reject); 49 | }) 50 | }) 51 | } 52 | 53 | Promise.customAll([ 54 | step1("hi"), 55 | step2("hey"), 56 | step3("key"), 57 | ]).then((res) => { 58 | console.log(res); 59 | }).catch((err) => { 60 | console.log(err); 61 | }) 62 | 63 | 64 | // Approach 2 65 | const doThis = (time) => { 66 | return new Promise((res, rej) => { 67 | setTimeout(() => { 68 | if (time < 3000) rej("rejected"); 69 | else res(time); 70 | }); 71 | }); 72 | }; 73 | 74 | const helloWorld = () => { 75 | return Promise.resolve("hello world"); 76 | }; 77 | 78 | const customPromiseAll = (taskArr) => { 79 | let results = []; 80 | let completedPromises = 0; 81 | return new Promise((res, rej) => { 82 | taskArr.forEach((pro, index) => { 83 | pro 84 | .then((val) => { 85 | results[index] = val; 86 | completedPromises += 1; 87 | 88 | if (completedPromises == taskArr.length) res(results); 89 | }) 90 | .catch((err) => rej(err)); 91 | }); 92 | }); 93 | }; 94 | 95 | customPromiseAll([doThis(3000), doThis(4000), doThis(3000), helloWorld()]) 96 | .then((res) => console.log(res)) 97 | .catch((err) => console.log(err)); 98 | 99 | 100 | -------------------------------------------------------------------------------- /Promises/index.js: -------------------------------------------------------------------------------- 1 | // callback hell 2 | console.log("started"); 3 | 4 | const step1 = (v, cb) => { 5 | setTimeout(() => { 6 | return cb(v + " Sam "); 7 | }, 800); 8 | } 9 | 10 | 11 | const step2 = (v, cb) => { 12 | setTimeout(() => { 13 | return cb(v + " Mes "); 14 | }, 100); 15 | } 16 | const step3 = (v, cb) => { 17 | setTimeout(() => { 18 | return cb(v + " Kes "); 19 | }, 100); 20 | } 21 | 22 | const message = step1("hey", (act) => { 23 | console.log(act); 24 | step2("hi", (action) => console.log(action)); 25 | step3("bye", (val) => console.log(val)); 26 | }) 27 | 28 | 29 | console.log("stopped"); 30 | 31 | 32 | // Promises hell 33 | 34 | const step1 = (v) => { 35 | return new Promise((res, rej) => { 36 | setTimeout(() => { 37 | res(v + " Sam "); 38 | }, 800); 39 | }) 40 | 41 | } 42 | 43 | 44 | const step2 = (v) => { 45 | return new Promise((res, rej) => { 46 | setTimeout(() => { 47 | res(v + " Mes "); 48 | }, 800); 49 | }) 50 | } 51 | const step3 = (v) => { 52 | return new Promise((res, rej) => { 53 | setTimeout(() => { 54 | res(v + " Kes "); 55 | }, 800); 56 | }); 57 | } 58 | 59 | step1("hi") 60 | .then((res) => { 61 | console.log(res); 62 | step2("hey") 63 | .then((res) => { 64 | console.log(res); 65 | step3("key") 66 | .then((res) => { 67 | console.log(res); 68 | }) 69 | }) 70 | }) 71 | .catch((err) => { 72 | console.log(err); 73 | }) 74 | 75 | 76 | // Promise chaining 77 | step1("hi") 78 | .then((res) => { 79 | console.log(res); 80 | return step2("hey"); 81 | } 82 | ).then((res) => { 83 | console.log(res); 84 | return step3("key"); 85 | 86 | }).then((res) => { 87 | console.log(res); 88 | }) 89 | .catch((err) => { 90 | console.log(err); 91 | }) 92 | 93 | 94 | // Promise comb - all, race, any, allSettled 95 | const firstFetch = () => { 96 | return new Promise((res, rej) => { 97 | setTimeout(() => { 98 | res("THis is the first fetch"); 99 | }, 800) 100 | }) 101 | } 102 | 103 | const secondFetch = () => { 104 | return new Promise((res, rej) => { 105 | setTimeout(() => { 106 | res("This is the second fetch"); 107 | }, 400); 108 | }) 109 | } 110 | 111 | const thirdFetch = () => { 112 | return new Promise((res, rej) => { 113 | setTimeout(() => { 114 | rej("This promise rejected"); 115 | }, 200); 116 | }) 117 | } 118 | 119 | // All - return err even if 1 gets rejected 120 | let data = Promise.all([ 121 | firstFetch(), secondFetch(), thirdFetch() 122 | ]).then((res) => { 123 | console.log(res) 124 | }).catch((err) => { 125 | console.error(err) 126 | }) 127 | 128 | // All Settle - return all promises 129 | let data = Promise.allSettled([ 130 | firstFetch(), secondFetch(), thirdFetch() 131 | ]).then((res) => { 132 | console.log(res) 133 | }).catch((err) => { 134 | console.error(err) 135 | }) 136 | 137 | 138 | // Race - return first called promise( reject or successdoes not matter) 139 | let data = Promise.race([ 140 | firstFetch(), secondFetch(), thirdFetch() 141 | ]).then((res) => { 142 | console.log(res) 143 | }).catch((err) => { 144 | console.error(err) 145 | }) 146 | 147 | // Any - return first called success promise 148 | let data = Promise.any([ 149 | firstFetch(), secondFetch(), thirdFetch() 150 | ]).then((res) => { 151 | console.log(res) 152 | }).catch((err) => { 153 | console.error(err) 154 | }) 155 | 156 | 157 | // async await - optimized way 158 | const handlePromise = async () => { 159 | try { 160 | const msg1 = await step1("hi"); 161 | console.log(msg1); 162 | const msg2 = await step1("hey"); 163 | console.log(msg2); 164 | const msg3 = await step1("ki"); 165 | console.log(msg3); 166 | } catch (err) { 167 | console.log(err); 168 | } 169 | }; 170 | 171 | -------------------------------------------------------------------------------- /PrototypalInheritance/index.js: -------------------------------------------------------------------------------- 1 | 2 | let obj = { 3 | name: 'sam', 4 | city: 'hyderabad', 5 | getName: function(){ 6 | return `${this.name} lives in ${this.city}` 7 | } 8 | }; 9 | 10 | 11 | let obj2 = { 12 | name: 'mes', 13 | } 14 | 15 | // assigns properties of x object to y 16 | obj2.__proto__ = obj; 17 | 18 | console.log(obj.name); // sam 19 | console.log(obj2.name); // mes 20 | console.log(obj2.city); // hyderabad 21 | console.log(obj.getName()); // sam lives in hyderabad 22 | console.log(obj2.getName()); // mes lives in hyderabad 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Javascript-Concepts 2 | 3 | console.log("Hello World"); 4 | 5 | 6 | I Will be pushing JS concepts( mainly medium & advanced) along with different output based questions which are asked in interviews!! 7 | 8 | console.log("Stay Tuned"); 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Testing/UnitTesting/Jest/Readme.md: -------------------------------------------------------------------------------- 1 | Will be adding jest files here 2 | -------------------------------------------------------------------------------- /Testing/UnitTesting/Jest/index.js: -------------------------------------------------------------------------------- 1 | const sorter = [ 2 | { name: 'saddm', age: '8' }, 3 | { name: 'smesam', age: '18' }, 4 | { name: 'dd', age: '81' }, 5 | ]; 6 | 7 | const sortByAge = () => { 8 | const value = sorter.sort((a, b) => { 9 | return a.age - b.age; 10 | }); 11 | 12 | return value; 13 | }; 14 | 15 | console.log(sortByAge()); 16 | 17 | module.exports = { sortByAge }; -------------------------------------------------------------------------------- /Testing/UnitTesting/Jest/index.test.js: -------------------------------------------------------------------------------- 1 | const { sortByAge } = require('./index'); 2 | 3 | test("testing 1st index", () => { 4 | const data = sortByAge(); 5 | expect(data[0].name).toBe("saddm") 6 | }) 7 | 8 | 9 | test("testing length", () => { 10 | const data = sortByAge(); 11 | expect(data.length).toBe(3) 12 | }) -------------------------------------------------------------------------------- /VanillaUI/1. CenterDiv/Readme.md: -------------------------------------------------------------------------------- 1 | Different ways to center div 2 | -------------------------------------------------------------------------------- /VanillaUI/1. CenterDiv/index.css: -------------------------------------------------------------------------------- 1 | #rootDiv { 2 | display: flex; 3 | flex-wrap: wrap; 4 | gap: 50px; 5 | } 6 | 7 | .parentClass { 8 | width: 400px; 9 | height: 400px; 10 | background-color: red; 11 | } 12 | 13 | .childClass { 14 | width: 100px; 15 | height: 100px; 16 | background-color: blue; 17 | 18 | display: flex; 19 | align-items: center; 20 | justify-content: center; 21 | color: white; 22 | } 23 | 24 | #parent1 { 25 | position: relative; 26 | } 27 | 28 | #child1 { 29 | position: absolute; 30 | top: 50%; 31 | left: 50%; 32 | transform: translate(-50%, -50%); 33 | } 34 | 35 | #parent2 { 36 | position: relative; 37 | } 38 | 39 | #child2 { 40 | position: absolute; 41 | top: 0; 42 | bottom: 0; 43 | left: 0; 44 | right: 0; 45 | margin: auto; 46 | } 47 | 48 | #parent3 { 49 | display: flex; 50 | align-items: center; 51 | justify-content: center; 52 | } 53 | 54 | #parent4 { 55 | display: flex; 56 | justify-content: center; 57 | } 58 | 59 | #child4 { 60 | align-self: center; 61 | } 62 | 63 | #parent5 { 64 | display: flex; 65 | } 66 | 67 | #child5 { 68 | margin: auto; 69 | } 70 | 71 | #parent6 { 72 | display: grid; 73 | justify-content: center; 74 | align-items: center; 75 | } 76 | 77 | #parent7 { 78 | display: grid; 79 | place-items: center; 80 | } 81 | 82 | #parent8 { 83 | display: grid; 84 | } 85 | 86 | #child8 { 87 | align-self: center; 88 | justify-self: center; 89 | } 90 | 91 | #parent9 { 92 | display: grid; 93 | } 94 | 95 | #child9 { 96 | margin: auto; 97 | } 98 | 99 | #parent10 { 100 | display: grid; 101 | } 102 | 103 | #child10 { 104 | place-self: center; 105 | } 106 | -------------------------------------------------------------------------------- /VanillaUI/1. CenterDiv/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | hey 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /VanillaUI/1. CenterDiv/index.js: -------------------------------------------------------------------------------- 1 | (() => { 2 | const arr = Array.from({ length: 10 }); 3 | 4 | const makeDiv = (index) => { 5 | const rootElement = document.querySelector("#rootDiv"); 6 | 7 | const parentDiv = document.createElement("div"); 8 | parentDiv.classList.add("parentClass"); 9 | parentDiv.id = `parent${index + 1}`; 10 | 11 | const childDiv = document.createElement("div"); 12 | childDiv.classList.add("childClass"); 13 | childDiv.id = `child${index + 1}`; 14 | 15 | childDiv.textContent = index + 1; 16 | 17 | parentDiv.appendChild(childDiv); 18 | rootElement.appendChild(parentDiv); 19 | }; 20 | 21 | arr.forEach((item, index) => { 22 | makeDiv(index); 23 | }); 24 | })(); 25 | -------------------------------------------------------------------------------- /this_keyword/index.js: -------------------------------------------------------------------------------- 1 | // "this" keyword refers to an object based on the context its called in 2 | 3 | // Normal func vs arrow func 4 | this.name = "user"; 5 | let user = { 6 | name: 'sam', 7 | getNormalName: function () { 8 | console.log(this.name); 9 | }, 10 | getArrowName: () => { 11 | console.log(this.name); 12 | } 13 | } 14 | 15 | user.getNormalName(); // sam - refers to immediate parent 16 | user.getArrowName(); // user - refers to normal parent func 17 | 18 | // In class 19 | class user { 20 | constructor(n) { 21 | this.name = n; 22 | } 23 | 24 | getName() { 25 | console.log(this.name); 26 | } 27 | } 28 | 29 | const User = new user("key"); 30 | User.getName(); // key 31 | 32 | 33 | // Q1 - Output 34 | const user = { 35 | fN: 'Sam', 36 | getName() { 37 | const fN = "mes"; 38 | return this.fN; 39 | } 40 | } 41 | 42 | console.log(user.getName()); // Sam - as this points to obj to func itself 43 | 44 | 45 | 46 | // Q2 - Output Fix 47 | 48 | function makeUser() { 49 | return { 50 | name: 'sam', 51 | ref: this, 52 | } 53 | } 54 | 55 | let user = makeUser(); 56 | console.log(user.ref.name); // undefined - this points to window 57 | Fix: 58 | 59 | function makeUser() { 60 | return { 61 | name: 'sam', 62 | ref() { 63 | return this; 64 | } 65 | } 66 | } 67 | 68 | let user = makeUser(); 69 | console.log(user.ref().name); // sam 70 | 71 | // Q3. Settimeout fix 72 | const user = { 73 | name: "sam", 74 | getName() { 75 | console.log(this.name); 76 | } 77 | } 78 | 79 | setTimeout( 80 | user.getName 81 | , 1000); // gives undefined - acts as a callback, refers to global window 82 | 83 | Fix: 84 | const user = { 85 | name: "sam", 86 | getName() { 87 | console.log(this.name); 88 | } 89 | } 90 | 91 | setTimeout(function () { 92 | user.getName() 93 | }, 1000); // sam - since created as a funciton 94 | 95 | 96 | // Q4. Implement calculator 97 | const calculator = { 98 | read() { 99 | this.a = +prompt("enter a", 0); 100 | this.b = +prompt("enter b", 01); 101 | 102 | }, 103 | 104 | sum() { 105 | return this.a + this.b; 106 | } 107 | } 108 | 109 | calculator.read(); 110 | console.log(calculator.sum()); 111 | 112 | // Q5. Output 113 | var length = 4; 114 | function cb() { 115 | console.log(this.length); 116 | } 117 | 118 | const obj = { 119 | length: 5, 120 | method(fN) { 121 | fN(); 122 | } 123 | } 124 | 125 | cb(); // 4 126 | obj.method(cb); // 4 - cb is called which refers to window obj 127 | 128 | // Q6. Output 129 | var length = 4; 130 | function cb() { 131 | console.log(this.length); 132 | } 133 | 134 | const obj = { 135 | length: 5, 136 | method(fN) { 137 | console.log(arguments); 138 | arguments[0](); 139 | } 140 | } 141 | 142 | cb(); // 4 143 | obj.method(cb, 3, 4); // 3 - Since arguments refer to the passed value(array) wich length prop 144 | 145 | 146 | // Q7. Implement Calc 147 | const calc = { 148 | total: 0, 149 | add(a) { 150 | this.total += a; 151 | return this; 152 | }, 153 | subt(a) { 154 | this.total -= a; 155 | return this; 156 | }, 157 | mul(a) { 158 | this.total *= a; 159 | return this; 160 | } 161 | } 162 | 163 | console.log(calc.add(3).mul(15).subt(3).total); // 42 164 | 165 | --------------------------------------------------------------------------------