Wednesday, April 3, 2024

Top 10 | JavaScript Coding Interview Question | Beginner Level

           JavaScript Coding Interview 

Q. No. 01/10: 

console.log("1"+"4"+"1")// 141
console.log(+"1"+"1"+"1")// 111
console.log(1 + + "1" + "1")// 21
console.log(1 - "1" + "1")// 01
console.log("A"-"B") // NAN

Q. No. 02/10: 

// Reverse String Question:
// Write JavaScript code to reverse a given string.
// Ex: world => dlrow
let string = "world";
// let string = "racecar";
let reverseString = string.split("").reverse().join("")
// console.log(reverseString)
// Palindrome Check:
//check a given string is a palindrome (reads the same forwards and backwards).
// Ex: racecar=> racecar; // Output: true
console.log(string === reverseString)

Q. No. 03/10:

const array1 = [1, 2, 3, 4, 5];
const array2 = [3, 4, 5, 6, 7];
// Output: [1, 2, 3, 4, 5, 6, 7]

const combinedArray = [...array1,...array2]
// console.log(combinedArray)
const removeDuplicates = Array.from(new Set(combinedArray))
console.log(removeDuplicates)


Q. No. 04/10:

const employees = [
    { id: 1, name: 'Mahesh', department: 'HR', salary: 50000 },
    { id: 2, name: 'Hema', department: 'Engineering', salary: 60000 },
    { id: 3, name: 'Maruthi', department: 'Marketing', salary: 55000 },
    ];
    // Can you explain how to retrieve an employee by their ID,
    // filter employees by department,
    // and calculate the average salary of all employees using JavaScript?"
function getEmployeeById(id){
    return employees.find(employee=>employee.id === id)
}
// console.log(getEmployeeById(1))
function getEmployeesByDepartment(department){
    return employees.filter(employee=>employee.department === department)
}
// console.log(getEmployeesByDepartment("HR"))
const totalSalary = employees.reduce((total,employee)=>total+employee.salary, 0)
console.log(totalSalary)
const getAverageSalary = totalSalary/employees.length;
console.log(getAverageSalary)


Q. No 05/10:

// Could you explain how the formatDate function works, especially regarding the
usage of methods like getDate(), getMonth(), getFullYear(), toString(), and
padStart()?"
function formatDate(date){
    const day = date.getDate().toString().padStart(2, "0")
    const month = (date.getMonth() + 1).toString().padStart(2, "0")
    const year = date.getFullYear()
    return `${day}/${month}/${year}`
}
console.log(formatDate(new Date()))


Q. No 06/10:

// "Could you explain the functionality of the calculator function, including how
it processes addition, subtraction, multiplication, and division operations
using a switch statement?"
function calculator(operator, num1, num2) {
    switch (operator) {
        case '+':
            return num1 + num2;
        case '-':
            return num1 - num2;
        case '*':
            return num1 * num2;
        case '/':
            return num1 / num2;
        default:
            return "Invalid operator";
    }
}
console.log(calculator("+", 6,3))

// Output: 9

Q. No 07/10:

// check prime Number
function isPrime(num) {
    if (num <= 1) {
        return false;
    }
    for (let i = 2; i <= Math.sqrt(num); i++) {
        if (num % i === 0) {
            return false;
        }
    }
    return true;
}
console.log(isPrime(2))

// Output: true

Q. No 08/10:

// Factorial
function factorial(n) {
    if (n === 0 || n === 1) {
        return 1;
    }
    return n * factorial(n - 1);
}
console.log(factorial(5))

//Output : 120


Q. No 09/10:

function printDiamond(height){
    // Upper part of the diamond
    for(let i=1; i<= height;i++){
        let row = " ";
        for(let j=1; j<= height-i;j++){
            row = row + " "

        }
        for(let k = 1; k<= 2*i-1; k++){
            row = row + "*"
        }
        console.log(row)
    }

    // Lower part of the diamond
    for(let i=height-1; i>=1;i--){
        let row = " ";
        for(let j=1; j<= height-i;j++){
            row = row + " "

        }
        for(let k = 1; k<= 2*i-1; k++){
            row = row + "*"
        }
        console.log(row)
    }
}

printDiamond(5)

Q. No 10/10:

let string = "hema coding school";

let capitalizeWords = string.split(" ").map(word=>word.toUpperCase().charAt()
+ word.slice(1)).join(" ")

console.log(capitalizeWords)





Monday, March 18, 2024

Day 7 || Real-time Bank Project Using MERN

                Hema Coding Bank Application

Day 7: 

Image:







WithdrawForm.js
import React, { useState } from "react";
import axios from "axios";
import Swal from "sweetalert";
import "./WithdrawalForm.css";
import logoImage from "../../src/Images/Logo.png";

const WithdrawalForm = ({ customer, upadetBalance }) => {
  const [withdrawalData, setWithdrawalData] = useState({
    username: customer.username,
    accountNumber: customer.accountNumber,
    withdrawalAmount: "",
    withdrawalType: "",
  });
  const handelSubmit = async (e) => {
    e.preventDefault();
    console.log(withdrawalData);
    try {
      const response = await axios.post(
        "http://localhost:3001/api/withdraw",
        withdrawalData
      );
      console.log(response.data);
      upadetBalance(response.data.balance);

      Swal({
        title: "Deposit Successful!",
        text: `Amount deposited: ${withdrawalData.withdrawalAmount}`,
        icon: "success",
      });
    } catch (error) {
      console.error("Withdraw failed", error);
    }
  };
  const handleClear = () => {
    setWithdrawalData({
      withdrawalAmount: "",
      withdrawalType: "",
    });
  };
  return (
    <div className="withdraw-container">
      <div className="image-withdraw-container"></div>

      <div className="text-withdraw-container">
        <img src={logoImage} alt="Hema Coding Bank logo" />
        <form onSubmit={handelSubmit}>
          <h2>Withdrawal Form :</h2>
          <p>Username:{customer.username} </p>
          <p>Account Number:{customer.accountNumber}</p>
          <label>Withdrawal Amount:</label>
          <input
            type="number"
            placeholder="Withdrawl Amount"
            value={withdrawalData.withdrawalAmount}
            onChange={(e) =>
              setWithdrawalData({
                ...withdrawalData,
                withdrawalAmount: e.target.value,
              })
            }
            required
          />
          <label>Withdrawal Type:</label>
          <input
            type="text"
            placeholder="Withdrawal Type"
            value={withdrawalData.withdrawalType}
            onChange={(e) =>
              setWithdrawalData({
                ...withdrawalData,
                withdrawalType: e.target.value,
              })
            }
            required
          />
          <button type="submit">Withdraw</button>
          <button type="submit" onClick={handleClear}>
            Clear
          </button>
        </form>
      </div>
    </div>
  );
};

export default WithdrawalForm;


WithdrawForm.css
.withdraw-container{
    display: flex;
}
.image-withdraw-container{
    background-image: url("../Images/Withdraw.jpg");
    background-size: 100% 100%;
    width: 130vh;
    height: 90vh;
}
.text-withdraw-container{
    border: 1px solid rgba(0, 0, 0, 0.2);
    margin: 20px;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.text-withdraw-container input{
    border: 1px solid rgb(131, 140, 239);
    padding: 1vw 1vw;
    border-radius: 10px;
    width: 300px;
    display: flex;
    margin: 5px;
    margin-left: 40px;
    color: #ba1919;
}
.text-withdraw-container button{
    border: 1px solid rgb(131, 140, 239);
    padding: 0.8vw 1vw;
    border-radius: 10px;
    margin: 5px;
    margin-left: 40px;
}
.text-withdraw-container img{
    height: 60px;
    padding: 20px;
}
.text-withdraw-container h2{
    color: #333366;
    padding-left: 40px;
}
.text-withdraw-container  label{
    padding-left: 40px;
}

App.js
import "./App.css";
import Home from "./Home";
import Login from "./Forms/Login";
import Registration from "./Forms/Registration";
import AccountDetails from "./Forms/AccountDetails";
import { Routes, Route, Link, useNavigate } from "react-router-dom";
import { useState } from "react";
import DepositForm from "./Forms/DepositForm";
import WithdrawalForm from "./Forms/WithdrawalForm";
function App() {
  const navigate = useNavigate();
  const [customer, setCustomer] = useState();
  const [updatedBalance, setUpdatedBalance] = useState(0);
  const upadetBalance = (newBalance) => {
    setUpdatedBalance(newBalance);
  };
  console.log(updatedBalance);
  const updateCustomer = (userData) => {
    setCustomer(userData);
    console.log(userData);
  };
  const handleLogout = () => {
    navigate("/login");
    setCustomer(null);
  };
  return (
    <div>
      <nav>
        <ul>
          <li>
            <Link className="nav-link" to="/">
              Home
            </Link>
          </li>
          {!customer ? (
            <>
              <li>
                <Link className="nav-link" to="/login">
                  Login
                </Link>
              </li>
              <li>
                <Link className="nav-link" to="/register">
                  Register
                </Link>
              </li>
            </>
          ) : (
            <>
              <li>
                <Link className="nav-link" to="/account-details">
                  Account Details
                </Link>
              </li>
              <li>
                <Link className="nav-link" to="/deposit">
                  Deposit
                </Link>
              </li>
              <li>
                <Link className="nav-link" to="/withdraw">
                  Withdraw
                </Link>
              </li>
              <li>
                <button onClick={handleLogout}>Logout</button>
              </li>
            </>
          )}
        </ul>
      </nav>

      <Routes>
        <Route path="/" element={<Home />} />
        <Route
          path="/login"
          element={<Login updateCustomer={updateCustomer} />}
        />
        <Route path="/register" element={<Registration />} />
        <Route
          path="/account-details"
          element={
            <AccountDetails
              customer={customer}
              updatedBalance={updatedBalance}
            />
          }
        />
        <Route
          path="/deposit"
          element={
            <DepositForm customer={customer} upadetBalance={upadetBalance} />
          }
        />
        <Route
          path="/withdraw"
          element={
            <WithdrawalForm customer={customer} upadetBalance={upadetBalance} />
          }
        />
      </Routes>
    </div>
  );
}

export default App;

Index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter as Router} from "react-router-dom";


const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Router>
    <App />
    </Router>
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();


Server.js

const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const cors = require("cors");

const app = express();
const port = 3001;

app.use(bodyParser.json());
app.use(cors());

mongoose.connect("mongodb://localhost:27017/Hema_Coding_Bank", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
const db = mongoose.connection;

db.once("open", () => {
  console.log("Connected to MongoDB");
});

const userSchema = new mongoose.Schema({
  username: String,
  password: String,
  accountNumber: Number,
  branch: String,
  phoneNumber: Number,
  balance: {
    type: Number,
    default: 0,
  },
});

const Customer = mongoose.model("Customer", userSchema);

app.post("/api/signup", async (req, res) => {
  try {
    const { username, password, accountNumber, branch, phoneNumber } = req.body;
    const newCustomer = new Customer({
      username,
      password,
      accountNumber,
      branch,
      phoneNumber,
    });
    await newCustomer.save();
    res.status(201).json({ message: "User created successfully" });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: "Internal server error" });
  }
});

app.post("/api/login", async (req, res) => {
  try {
    const { username, password } = req.body;
    const customer = await Customer.findOne({ username });
    if (!customer) {
      res.status(401).json({
        message: "Invalid username ",
      });
    }
    if (customer.password !== password) {
      res.status(401).json({
        message: "Invalid password ",
      });
    }
    res.status(200).json({
      message: "Login successful",
      customer: {
        username: customer.username,
        accountNumber: customer.accountNumber,
        branch: customer.branch,
        phoneNumber: customer.phoneNumber,
        balance: customer.balance,
      },
    });
    console.log(customer);
  } catch (error) {
    console.error(error);
    res.status(500).json({
      message: "Internal server error",
    });
  }
});

const depositSchema = new mongoose.Schema({
  username: String,
  accountNumber: Number,
  date: String,
  depositAmount: Number,
  depositType: String,
});
const Deposit = mongoose.model("Deposit", depositSchema);

app.post("/api/deposit", async (req, res) => {
  try {
    const { username, accountNumber, date, depositAmount, depositType } =
      req.body;
    console.log(req.body);
    const customer = await Customer.findOne({ username, accountNumber });
    console.log(customer);
    console.log(customer.balance);
    console.log(depositAmount);
    customer.balance = Number(customer.balance) + Number(depositAmount);
    console.log(customer.balance);
    await customer.save();

    if (!customer) {
      res.status(401).json({ message: "Invalid username and account number" });
    }
    const newDeposit = new Deposit({
      username,
      accountNumber,
      date,
      depositAmount,
      depositType,
    });

    await newDeposit.save();
    return res.status(200).json({
      message: "Deposit successful",
      balance: customer.balance,
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({
      message: "Internal server error",
    });
  }
});
const withdrawalSchema = new mongoose.Schema({
  username: String,
  accountNumber: Number,
  withdrawalAmount: Number,
  withdrawalType: String,
  date: String,
});

const Withdrawal = mongoose.model("Withdrawal", withdrawalSchema);
app.post("/api/withdraw", async (req, res) => {
  try {
    const { username, accountNumber, withdrawalAmount, withdrawalType, date } =
      req.body;

    const customer = await Customer.findOne({ username, accountNumber });
    console.log(req.body);
    console.log(customer.balance);
    console.log(withdrawalAmount);
    customer.balance = customer.balance - withdrawalAmount;
    console.log(customer.balance);
    await customer.save();

    return res.status(200).json({
      message: "Withdrawal successful",
      balance: customer.balance,
    });
    const newWithdrawal = new Withdrawal({
      username,
      accountNumber,
      withdrawalAmount,
      withdrawalType,
      date,
    });
    await newWithdrawal.save();
  } catch (error) {
    console.error(error);
    res.status(500).json({
      message: "Internal server error",
    });
  }
});
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});










Top 10 | JavaScript Coding Interview Question | Beginner Level

               JavaScript Coding Interview  Q. No. 01/10:  console . log ( "1" + "4" + "1" ) // 141 console . ...