Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts
Tuesday, 21 January 2025
Monday, 20 January 2025
JavaScript Pure and Impure Functions.
1. JavaScript Pure Functions.
JavaScript Pure Function Without modifying value return. like predictable out value.
function add(x) {
return x + 1;
}
console.log(add(10)); // output : 11
console.log(add(11)); // output : 12
console.log(add(12)); // output : 13
2. JavaScript Impure Functions.
JavaScript Impure Function value is change every time.
let x = 10;
function add() {
return x++;
}
console.log(add()); // output : 10
console.log(add()); // output : 11
console.log(add()); // output : 12
JavaScript Spread and Rest Operators.
1. JavaScript Spread Operator.
JavaScript spread operator used for modifying or merging array.
let a = [1,2,3,3];
let b = [4,5,6,7,3];
let output = [...a, ...b];
console.log('output--->', output);
// output : output---> [1, 2, 3, 3, 4, 5, 6, 7, 3]
2. JavaScript Rest Operator.
JavaScript Rest Operator used for We don't know the number of parameters come in the function.
function call(...data) {
console.log('data---->', data);
}
call(1,2,3,4,5);
// output : data----> [ 1, 2, 3, 4, 5 ]
JavaScript Closures, Callbacks and Callback Hell, Generator Func. ,Currying Function, Pure - Impure Function
1. JavaScript Closures.
Closures is the combination of a bundled function.
Closures gives you access to an outer function's scope from an inner function.
function init() {
var name = 'Mozilla';
function displayName() {
console.log('name --->', name);
// output : name ---> Mozilla
}
displayName();
}
init();
2. JavaScript Callbacks.
Function passed as an argument.
function test1(name, callback) {
console.log('name---->', name);
callback();
}
function test2() {
console.log('test2---->');
}
test1("Ankit", test2);
//output :
// name----> Ankit
// test2---->
3. JavaScript Callback Hell.
Every callback depends / waits for the previous callback.
setTimeout(() => {
console.log('test 1--->');
setTimeout(() => {
console.log('test 2--->');
}, 2000);
}, 5000);
// output :
// test 1--->
// test 2--->
4. JavaScript Generator Function.
A Generator Function is a special function in JavaScript that can pause its execution and resume later. It returns values one by one instead of returning all values at once.
It is created using the function* syntax and uses the yield keyword.
Useful for lazy loading, pagination, large data processing, and generating sequences.
function* genFunc() {
yield 1;
yield 2;
}
let abcFunc = genFunc();
console.log(abcFunc.next().value); // 1
console.log(abcFunc.next().value); // 2
console.log(abcFunc.next().value); // undefined
5. JavaScript Currying Function.
Currying is a technique in JavaScript where a function with multiple arguments is converted into a sequence of functions, each taking one argument at a time.
function sendEmail(to) { return function (from) { return function (body) { return to + ' - ' + from + ' - ' + body; } }}
let to = sendEmail('to@gmail.com');let from = to('from@gmail.com');console.log(from('Body data'));// output : to@gmail.com - from@gmail.com - Body data.
function sendEmail(to) { return function (from) { return function (body) { return to + ' - ' + from + ' - ' + body; } }}
console.log(sendEmail('to@gmail.com')('from@gmail.com')('Body data.'));// output : to@gmail.com - from@gmail.com - Body data.
function sendEmail(to) {
return function (from) {
return function (body) {
return to + ' - ' + from + ' - ' + body;
}
}
}
let to = sendEmail('to@gmail.com');
let from = to('from@gmail.com');
console.log(from('Body data'));
// output : to@gmail.com - from@gmail.com - Body data.
function sendEmail(to) {
return function (from) {
return function (body) {
return to + ' - ' + from + ' - ' + body;
}
}
}
console.log(sendEmail('to@gmail.com')('from@gmail.com')('Body data.'));
// output : to@gmail.com - from@gmail.com - Body data.
//using arrow functionconst sendemail = (to) => (from) => (body) => { return to + ' - ' + from + ' - ' + body};console.log('sendemail--->', sendemail('to@gmail.com')('from@gmail.com')('Body data.'));// output : sendemail---> to@gmail.com - from@gmail.com - Body data.
//using arrow function
const sendemail = (to) => (from) =>
(body) => { return to + ' - ' + from + ' - ' + body};
console.log('sendemail--->',
sendemail('to@gmail.com')('from@gmail.com')('Body data.'));
// output : sendemail---> to@gmail.com - from@gmail.com - Body data.
let add = (a) => (b) => (c) => a + b + c;console.log(add(1)(2)(3)); // output : 6
let add = (a) => (b) => (c) => a + b + c;
console.log(add(1)(2)(3)); // output : 6
6. Pure - Impure Function.
Pure Function : Always returns the same output for the same input. Like predictable output.
const pFunc = (a) => {
return a + 1;
};
console.log(pFunc(2)); // 3
console.log(pFunc(2)); // 3
Impure Function : Return different results for the same input.
let a = 2;
const impFunc = () => {
return a++;
};
console.log("impFunc--->", impFunc()); // 2
console.log("impFunc--->", impFunc()); // 3
console.log("impFunc--->", impFunc()); // 4
Saturday, 18 January 2025
Javascript small practical interview questions and answers.
1. Reverse string JavaScript.
let name = "Ankit";
let revName = name.split("").reverse().join("");
console.log("revName---->", revName); // output : revName----> tiknA
let revNames = "";for(let i = name.length-1; i >= 0; i--) { revNames += name[i];}console.log("revNames---->", revNames); // output : revNames----> tiknA
let revNames = "";
for(let i = name.length-1; i >= 0; i--) {
revNames += name[i];
}
console.log("revNames---->", revNames); // output : revNames----> tiknA
// input = "I Love My India" : Output is : I evoL yM aidnI let inputWord = "I Love My India";
let newString = inputWord.split(" ").map((x) => { return x.split("").reverse().join("");});console.log(newString.join(" "));
// input = "I Love My India" : Output is : I evoL yM aidnI
let inputWord = "I Love My India";
let newString = inputWord.split(" ").map((x) => {
return x.split("").reverse().join("");
});
console.log(newString.join(" "));
// Example: Input: "Maulik", rotate by 2 → Output: "ulikMa"function outputString(text, num) { let res = ""; for (i = num; i < text.length; i++) { res += text[i]; } for (i = 0; i < num; i++) { res += text[i]; }
return res;}console.log(outputString("Maulik", 2));
// Example: Input: "Maulik", rotate by 2 → Output: "ulikMa"
function outputString(text, num) {
let res = "";
for (i = num; i < text.length; i++) {
res += text[i];
}
for (i = 0; i < num; i++) {
res += text[i];
}
return res;
}
console.log(outputString("Maulik", 2));
// =======get First Non Repeating also show count repeat==============function getFirstNonRepeating(text) { let count = {};
for (let char of text) { count[char] = (count[char] || 0) + 1; }
console.log(count);
for (let char of text) { if (count[char] == 1) { return char; } }}console.log(getFirstNonRepeating("aazbbcdde")); //z
// =======get First Non Repeating also show count repeat==============
function getFirstNonRepeating(text) {
let count = {};
for (let char of text) {
count[char] = (count[char] || 0) + 1;
}
console.log(count);
for (let char of text) {
if (count[char] == 1) {
return char;
}
}
}
console.log(getFirstNonRepeating("aazbbcdde")); //z
// sort string numbers and return in stringlet strings = "1846879234";console.log(strings.split("").sort((a, b) => a - b).join(""));
// sort string numbers and return in string
let strings = "1846879234";
console.log(strings.split("").sort((a, b) => a - b).join(""));
2. Remove duplicate string from array JavaScript.
let cityName = ["pune", "ahmedabad", "nagpur", "pune"];
let uniqName = [...new Set(cityName)];
console.log("uniqName--->", uniqName);
// output : uniqName---> [ 'pune', 'ahmedabad', 'nagpur' ]
let uniqeCityName = [];let filterCityName = cityName.map(x => { uniqeCityName.indexOf(x) === -1 && uniqeCityName.push(x);});console.log("uniqeCityName--->", uniqeCityName); // output : uniqeCityName---> [ 'pune', 'ahmedabad', 'nagpur' ]
let uniqeCityName = [];
let filterCityName = cityName.map(x => {
uniqeCityName.indexOf(x) === -1 && uniqeCityName.push(x);
});
console.log("uniqeCityName--->", uniqeCityName);
// output : uniqeCityName---> [ 'pune', 'ahmedabad', 'nagpur' ]
Merge Two Arrays and Remove Duplicate Objects Based on Email in JavaScript.
const array1 = [
{ name: "shan", email: "shan@abc.com" },
{ name: "raj", email: "raj@abc.com" },
{ name: "raj", email: "raj@gmail.com" },
];
const array2 = [
{ name: "shan1", email: "shan1@abc.com" },
{ name: "raj", email: "raj@abc.com" },
{ name: "ram", email: "ram@abc.com" },
];
let mrgArray = [...array1, ...array2];
// console.log(mrgArray);
let unqdata = [];
let setEmail = [];
mrgArray.map((x) => {
if (setEmail.indexOf(x.email) == -1) {
setEmail.push(x.email);
unqdata.push(x);
}
});
console.log(unqdata);
3. Swapping of two numbers JavaScript.
let a = 10, b = 20, tmp;
tmp=a; a=b; b=tmp;
console.log("a,b--->", a,b);
// output : a,b---> 20 10
let swapNumber = [a,b] = [b,a]; // Destructuring es6 methodconsole.log("swapNumber---->", swapNumber); // output : swapNumber----> [ 10, 20 ]
let swapNumber = [a,b] = [b,a]; // Destructuring es6 method
console.log("swapNumber---->", swapNumber);
// output : swapNumber----> [ 10, 20 ]
Extracting Nested Object Values Using Destructuring in JavaScript
// Using object destructuring : input is like : emp
const emp = {
id: 1,
name: "ABC",
child: { id: 2, name: "pqr", subchild: { id: 3, name: "asd" } },
};
// output is like : 1 ABC 2 pqr 3 asd
// Solution : Working Function
let {
id,
name,
child: {
id: childId,
name: childName,
subchild: { id: subchildId, name: subchiName },
},
} = emp;
console.log(id, name, childId, childName, subchildId, subchiName);
4. Find highest and Second highest JavaScript.
let numArray = [6,7,1,2,3,99,4,5,1,2,33,33,3];
let maxNumer = Math.max(...numArray);
console.log('maxNumer--->', maxNumer);
// output : maxNumer---> 99
let numArray = [6,7,1,2,3,99,4,5,1,2,33,33,3];let highestNum, secondHigh;numArray.map(x => { if(!highestNum) highestNum = x; if(highestNum && x > highestNum){ secondHigh = highestNum ; highestNum = x; } else { if(x > secondHigh) secondHigh = x; }});console.log('highestNum, secondHigh--->', highestNum, secondHigh);// output : highestNum, secondHigh---> 99 33
let numArray = [6,7,1,2,3,99,4,5,1,2,33,33,3];
let highestNum, secondHigh;
numArray.map(x => {
if(!highestNum) highestNum = x;
if(highestNum && x > highestNum){
secondHigh = highestNum ;
highestNum = x; }
else {
if(x > secondHigh) secondHigh = x;
}
});
console.log('highestNum, secondHigh--->', highestNum, secondHigh);
// output : highestNum, secondHigh---> 99 33
Order to first all numbers and after show all zeros in array.
let arr = [2, 5, 0, 6, 1, 0, 4, 0, 9, 0, 0];
let nonZeros = [];
let zeros = [];
arr.map((x) => {
if (x != 0) nonZeros.push(x);
else zeros.push(x);
});
console.log([...nonZeros, ...zeros]);
// output is : [2, 5, 6, 1, 4, 9, 0, 0, 0, 0, 0]
Two Number Sum. Return array index.
// Input: ((nums = [2, 7, 11, 15]), (target = 9)); Output: [0, 1];
// Input: ((nums = [3, 2, 4]), (target = 6)); Output: [1, 2];
function twoSum(nums, target) {
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
// console.log("test ===>", nums[i], nums[j], target);
if (nums[i] + nums[j] === target) {
return [i, j];
}
}
}
}
console.log("test 1-->", twoSum([2, 7, 11, 15], 9));
console.log("test 1-->", twoSum([3, 2, 4], 6));
Make flat array and remove duplicate also with zero index multiple by 10.
let arr = [1, 2, 2, 9, 3, [4, 5], [6, 7, 8, 8]];
console.log([...new Set(arr.flat())]); // using function
let resFlatArray = [];
arr.map((x, index) => {
if (Array.isArray(x)) {
x.map((y, index) => {
resFlatArray.indexOf(y) == -1 &&
resFlatArray.push(index == 0 ? y * 10 : y);
});
} else {
resFlatArray.indexOf(x) == -1 && resFlatArray.push(index == 0 ? x * 10 : x);
}
});
console.log(resFlatArray);
//Output : [10, 2, 9, 3, 40, 5, 60, 7, 8];
Flat this array without any inbuilt method
const arr = [1, 2, [3, [4, 5], 6], 7];
function flattenArray(input) { let result = [];
function helper(element) { // If the element is NOT an array → push directly if (typeof element !== "object") { result.push(element); return; }
// Manually loop array elements (no built-ins) for (let i = 0; i < element.length; i++) { helper(element[i]); } }
helper(input); return result;}
console.log(flattenArray(arr));// Output: [1, 2, 3, 4, 5, 6, 7]
const arr = [1, 2, [3, [4, 5], 6], 7];
function flattenArray(input) {
let result = [];
function helper(element) {
// If the element is NOT an array → push directly
if (typeof element !== "object") {
result.push(element);
return;
}
// Manually loop array elements (no built-ins)
for (let i = 0; i < element.length; i++) {
helper(element[i]);
}
}
helper(input);
return result;
}
console.log(flattenArray(arr));
// Output: [1, 2, 3, 4, 5, 6, 7]
5. Sorting array in Ascending and Descending order JavaScript.
let numArray = [6,7,1,2,3,99,4,5,1,2,33,33,3];
// Sort in ascending order
let ascending = [...numArray].sort((a, b) => a - b);
console.log("ascending :", ascending);
// output : ascending : [ 1, 1, 2, 2, 3, 3, 4, 5, 6, 7, 33, 33, 99 ]
// Sort in descending order
let descending = [...numArray].sort((a, b) => b - a);
console.log("descending :", descending);
// output : descending : [ 99, 33, 33, 7, 6, 5, 4, 3, 3, 2, 2, 1, 1 ]
let sortString = ["mumbai", "pune", "ahmedabad", "botad"];let ascStringSortFun = sortString.sort();console.log("ascStringSortFun---->", ascStringSortFun); // output : ascStringSortFun----> [ 'ahmedabad', 'botad', 'mumbai', 'pune' ]
let descStringSortFun = sortString.sort().reverse();console.log("descStringSortFun---->", descStringSortFun); // output : descStringSortFun----> [ 'pune', 'mumbai', 'botad', 'ahmedabad' ]
let sortString = ["mumbai", "pune", "ahmedabad", "botad"];
let ascStringSortFun = sortString.sort();
console.log("ascStringSortFun---->", ascStringSortFun);
// output : ascStringSortFun----> [ 'ahmedabad', 'botad', 'mumbai', 'pune' ]
let descStringSortFun = sortString.sort().reverse();
console.log("descStringSortFun---->", descStringSortFun);
// output : descStringSortFun----> [ 'pune', 'mumbai', 'botad', 'ahmedabad' ]
6. Find Even and Odd Numbers in an Array in JavaScript.
let numArray = [6,7,1,2,3,99,4,5,1,2,33,33,3];
let evenNum = numArray.filter(x => {
return x % 2 == 0 && x;
});
console.log('evenNum--->', evenNum);
// output : evenNum---> [ 6, 2, 4, 2 ]
let oddNum = numArray.filter(x => {
return x % 2 != 0 && x;
});
console.log('oddNum--->', oddNum);
// output : oddNum---> [7, 1, 3, 99, 5, 1, 33, 33, 3]
7. Unique Values - Remove duplicates in an Array JavaScript.
let numArray = [6,7,1,2,3,99,4,5,1,2,33,33,3];
let unqArr = [...new Set(numArray)];
console.log("unqArr--->", unqArr);
// output : unqArr---> [6, 7, 1, 2, 3, 99, 4, 5, 33]
let numArray = [6,7,1,2,3,99,4,5,1,2,33,33,3];
let uniqeArray = [];let filterNumArray = numArray.map(x => { uniqeArray.indexOf(x) === -1 && uniqeArray.push(x);});console.log("uniqeArray--->", uniqeArray); // output : uniqeArray---> [ 6, 7, 1, 2, 3, 99, 4, 5, 33]
let numArray = [6,7,1,2,3,99,4,5,1,2,33,33,3];
let uniqeArray = [];
let filterNumArray = numArray.map(x => {
uniqeArray.indexOf(x) === -1 && uniqeArray.push(x);
});
console.log("uniqeArray--->", uniqeArray);
// output : uniqeArray---> [ 6, 7, 1, 2, 3, 99, 4, 5, 33]
8. Find unique values from two array JavaScript.
let num1 = [1,22,33,44,55,99];
let num2 = [55,66,22];
let uniqData = [...new Set([...num1, ...num2])];
console.log('uniqData--->', uniqData);
// output : uniqData---> [1, 22, 33, 44, 55, 99, 66]
9. Find, Map, Filter and Reduce JavaScript.
// find : return only one value, otherwise return undeifned.
// map : return : true, false and array data
// filter : condition match the return array data otherwise return [] array
// reduce : use for mathematic operation
let x = [1, 2, 33, 44, 55, 66];
let findData = x.find((val) => { return val > 44 });
console.log("findData--->", findData); // return single value
// output : findData---> 55
let mapData = x.map((val, index) => { return val + 100; });
console.log("mapData--->", mapData); // return array
// output : mapData---> [ 101, 102, 133, 144, 155, 166 ]
let filterData = x.filter((val, index, array) => { return val > 22; });
console.log("filterData---->", filterData); // return array
// output : filterData----> [ 33, 44, 55, 66 ]
let reduceSumData = x.reduce((total, val, index, array) => { return total + val; });
console.log("reduceSumData--->", reduceSumData); // return number value
// output : reduceSumData---> 201
10. Assume the output of example in JavaScript.
var bar = true;
console.log(bar + 2); // 3
console.log(bar + "xyz"); // truexyz
console.log(bar + true); // 2
console.log(bar + false); //1
var salary = "1000$";
(function () {
console.log("Original salary was " + salary); // undefined
var salary = "5000$";
console.log("My New Salary " + salary); // 5000$
})();
// Solution : Working Function
(function () {
var salary = "1000$";
console.log("Original salary was " + salary); // 1000$
var salary = "5000$";
console.log("My New Salary " + salary); // 5000$
})();
const user = {
name: "Jason",
greet: function () {
setTimeout(function () {
console.log(this.name); // undefined
}, 100);
},
};
user.greet();
// Solution : Working Function
const user = {
name: "Jason",
greet: function () {
setTimeout(() => { // correction
console.log(this.name); // Jason
}, 100);
},
};
user.greet();
// ********example 1**********
console.log("1");
setTimeout(() => {
console.log("2");
},0);
setTimeout(() => {
console.log("3");
});
console.log("4");
// output : 1 4 2 3
// ********example 2**********
function logger(a,b,a) {
console.log('a,b,a--->', a,b,a);
}
logger(1,2,3,4);
// output : a,b,a---> 3 2 3
// ********example 3**********
let aa = 5;
console.log('aa++--->',aa++);
// output : aa++---> 5
aa = 5;
console.log('++aa--->',++aa);
// output : ++aa---> 6
let bb = 5;
console.log('bb-- --->',bb--);
// output : bb-- ---> 5
bb = 5;
console.log('--bb --->',--bb);
// output : --bb ---> 4
// ********example 4**********
console.log(1);
for(let i=2;i<=10;i++){ console.log(i);}
setTimeout(() => { console.log(11)}, 3000)
let promise = new Promise((resolve, reject) => { setTimeout(() => { resolve('success') }, 500);})
setTimeout(() => { console.log(12)}, 500)
promise.then(res => { console.log(res)})
console.log(13);
// output : 1 2 3 4 5 6 7 8 9 10 13 success 12 11
// ********example 4**********
console.log(1);
for(let i=2;i<=10;i++){
console.log(i);
}
setTimeout(() => {
console.log(11)
}, 3000)
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('success')
}, 500);
})
setTimeout(() => {
console.log(12)
}, 500)
promise.then(res => {
console.log(res)
})
console.log(13);
// output : 1 2 3 4 5 6 7 8 9 10 13 success 12 11
11. Callbacks - Promises - Async/Await in JavaScript.
// *******callback********
function test3(callback) {
console.log('test3---->');
callback();
}
function test4() {
console.log('test4---->');
}
test3(test4);
// output :
// test3---->
// test4---->
// *******Promises***********
function test8() {
console.log('test8--->');
return new Promise((resolve, reject) => {
resolve();
// reject('reject error---->');
})
}
function test9() {
console.log('test9--->');
}
test8().then(test9).catch(e => console.log('e--->', e));
// output :
// test8--->
// test9--->
// *******Async/Await********
async function test1() {
console.log('test1---->');
await test2();
}
function test2() {
console.log('test2---->');
}
test1();
// output :
// test1---->
// test2---->
12. Event loop in JavaScript.
// ****event loop******
function test5() {
console.log('test5---->');
}
function test6() {
setTimeout(() => {
console.log('test6---->'); // execute after 5 second
}, 5000);
}
function test7() {
console.log('test7---->');
}
test5();
test6();
test7();
// output :
// test5---->
// test7---->
// test6---->
13. Event loop in JavaScript. Implement deepMerge, Arrays → concatenate, Objects → recursive merge
const a = {
user: { name: "Akshay", roles: ["admin"] },
settings: { theme: "dark" },
};
const b = {
user: { roles: ["editor"], age: 25 },
settings: { lang: "en" },
};
console.log(deepMerge(a, b));
// output :
{
user: { name: "Akshay", roles: ["admin", "editor"], age: 25 },
settings: { theme: "dark", lang: "en" }
}
// Solution :
function deepMerge(obj1, obj2) {
// If both are arrays → concatenate
if (Array.isArray(obj1) && Array.isArray(obj2)) {
return [...obj1, ...obj2];
}
// If both are objects → recursive merge
if (isObject(obj1) && isObject(obj2)) {
const result = {};
const keys = new Set([...Object.keys(obj1), ...Object.keys(obj2)]);
for (const key of keys) {
if (key in obj1 && key in obj2) {
result[key] = deepMerge(obj1[key], obj2[key]);
} else if (key in obj1) {
result[key] = obj1[key];
} else {
result[key] = obj2[key];
}
}
return result;
}
// Primitive values → obj2 overrides obj1
return obj2;
}
function isObject(value) {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
14. Correct and solve this function
function getUser(id) {
return setTimeout(() => {
return { id: id, name: "John" };
}, 500);
}
function getOrders(userId) {
return setTimeout(() => {
return [
{ id: 1, amount: 200 },
{ id: 2, amount: 300 },
];
}, 500);
}
async function getUserData() {
const user = await getUser(1);
const orders = await getOrders(1);
console.log({
user,
orders,
});
}
getUserData();
// Solution
function getUser(id) {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ id: id, name: "John" });
}, 500);
});
}
function getOrders(userId) {
return new Promise((resolve) => {
setTimeout(() => {
resolve([
{ id: 1, amount: 200 },
{ id: 2, amount: 300 },
]);
}, 500);
});
}
async function getUserData() {
const user = await getUser(1);
const orders = await getOrders(1);
console.log("user---->", user);
console.log("orders---->", orders);
// Combined Output:
// console.log({ user, orders });
}
getUserData();
// Output ::
// user----> { id: 1, name: "John" }
// orders----> [ { id: 1, amount: 200 }, { id: 2, amount: 300 } ]