Monday, 20 January 2025

JavaScript Spread and Rest Operators.

 


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, Currying.



JavaScript Closures, Callbacks and Callback Hell, Currying 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 Currying Function.

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 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.


Saturday, 18 January 2025

Javascript small practical interview questions and answers

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

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' ]

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 method
console.log("swapNumber---->", swapNumber);
// output : swapNumber----> [ 10, 20 ]

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

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' ]

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]

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.

// ********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

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---->


Friday, 27 December 2024

Clusters of Node.js

Clusters of Node.js

Node.js's cluster module, which allows for the creation of multiple instances of a Node.js application to utilize multiple CPU cores effectively.

Cluster is following round-robin approach.

Workload is equally distribute in our servers and Handling traffic.

Example of Cluster with Node.js

const express = require('express');
const cluster = require('cluster');
const os = require('os');

const PORT = 3300; // Server port
const numCPUs = os.cpus().length; // Total CPU cores available

if (cluster.isPrimary) {
  console.log(`Master process started with PID: ${process.pid}`);

  // Fork workers for each CPU core
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  // Listen for worker exit and optionally restart
  cluster.on('exit', (worker, code, signal) => {
    console.log(`Worker ${worker.process.pid} exited. Starting a new worker...`);
    cluster.fork(); // Optionally replace the dead worker
  });
} else {
  const app = express();

  // Middleware to log requests
  app.use((req, res, next) => {
    console.log(`Request handled by process ${process.pid}`);
    next();
  });

  // Example routes
  app.get('/', (req, res) => {
    res.send({
      message: `Handled by process ${process.pid}`,
      route: '/',
    });
  });

  app.get('/about', (req, res) => {
    res.send({
      message: `Handled by process ${process.pid}`,
      route: '/about',
    });
  });

  app.get('/contact', (req, res) => {
    res.send({
      message: `Handled by process ${process.pid}`,
      route: '/contact',
    });
  });

  // Start the server
  app.listen(PORT, () => {
    console.log(`Worker ${process.pid} started. Listening on port ${PORT}`);
  });
}

Thursday, 19 December 2024

Node.js handle uncaught exceptions

Node.js handle uncaught exceptions Node.js handle uncaught exceptions Node.js handle uncaught exceptions

const express = require('express');

const app = express();

// Middleware to parse JSON requests
app.use(express.json());

// A sample route
app.get('/', (req, res) => {
    res.send('Welcome to the Express.js app!');
});

// An example of a route with a potential error
app.get('/error', (req, res) => {
    throw new Error('This is an uncaught exception!');
});

// Global error handling middleware
app.use((err, req, res, next) => {
    console.error('Error caught by middleware:', err.message);
    res.status(500).json({ message: 'Internal Server Error' });
});

// Start the server
const PORT = 3000;
const server = app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

// Handle uncaught exceptions
process.on('uncaughtException', (err) => {
    console.error('Uncaught Exception:', err.message);
    console.error(err.stack);

    // Perform cleanup if necessary, then exit
    server.close(() => {
        console.log('Server closed due to uncaught exception');
        process.exit(1); // Exit with a failure code
    });
});

// Handle unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
    console.error('Unhandled Rejection at:', promise, 'reason:', reason);

    // Perform cleanup if necessary
    server.close(() => {
        console.log('Server closed due to unhandled rejection');
        process.exit(1); // Exit with a failure code
    });
});

Node.js with Sample Mock API

 Node.js with Sample : Mock API using express

const express = require('express');
const app = express();
const PORT = 3000;

// Mock data
const users = [
  { id: 1, name: 'John Doe', email: 'john.doe@example.com' },
  { id: 2, name: 'Jane Smith', email: 'jane.smith@example.com' },
  { id: 3, name: 'Sam Johnson', email: 'sam.johnson@example.com' },
];

// Middleware
app.use(express.json());

// Routes
// Get all users
app.get('/api/users', (req, res) => {
  res.status(200).json(users);
});

// Get user by ID
app.get('/api/users/:id', (req, res) => {
  const userId = parseInt(req.params.id, 10);
  const user = users.find(u => u.id === userId);
  if (user) {
    res.status(200).json(user);
  } else {
    res.status(404).json({ message: 'User not found' });
  }
});

// Add a new user
app.post('/api/users', (req, res) => {
  const { name, email } = req.body;
  const newUser = {
    id: users.length + 1,
    name,
    email,
  };
  users.push(newUser);
  res.status(201).json(newUser);
});

// Update a user by ID
app.put('/api/users/:id', (req, res) => {
  const userId = parseInt(req.params.id, 10);
  const userIndex = users.findIndex(u => u.id === userId);
  if (userIndex !== -1) {
    const { name, email } = req.body;
    users[userIndex] = { id: userId, name, email };
    res.status(200).json(users[userIndex]);
  } else {
    res.status(404).json({ message: 'User not found' });
  }
});

// Delete a user by ID
app.delete('/api/users/:id', (req, res) => {
  const userId = parseInt(req.params.id, 10);
  const userIndex = users.findIndex(u => u.id === userId);
  if (userIndex !== -1) {
    users.splice(userIndex, 1);
    res.status(204).send(); // No content
  } else {
    res.status(404).json({ message: 'User not found' });
  }
});

// Start the server
app.listen(PORT, () => {
  console.log(`Mock API is running at http://localhost:${PORT}`);
});

React useLayoutEffect Hook

useLayoutEffect Work synchronously. and useEffect work with asynchronously.

useEffect it fires synchronously after all DOM loading is done loading.

useLayoutEffect call before DOM update.

App.js file : use hook : useEffect and useLayoutEffect both, but in console you can check first render useLayoutHook. so you can some time calculation or other stuffs before render DOM, you can go with useLayoutEffect hook.

import { createContext, useState, useLayoutEffect, useEffect } from 'react';
import './App.css';

function App() {
  let [name, setName] = useState('Ankit Vyas');

  useEffect(() => {
    console.log('call useEffect.');
    setName('Vyas');
  }, []);

  useLayoutEffect(() => {
    console.log('call useLayoutEffect.');    
    setName('Ankit');
  }, []);

  return (
    <div className="App">  
      My name is : {name}
    </div>
  );
}

export default App;