0% found this document useful (0 votes)
7 views14 pages

WDF Unit 1 and 2 DN Exercises

The document provides a comprehensive guide on creating JavaScript applications, including a bank account object, merging customer and account data, a scientific calculator, a Tic Tac Toe game, and a palindrome checker. It includes code snippets for each application, demonstrating various JavaScript concepts such as objects, arrays, higher-order functions, and event handling. The document serves as a practical resource for learning JavaScript through hands-on projects.

Uploaded by

oopsitsmysteria
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views14 pages

WDF Unit 1 and 2 DN Exercises

The document provides a comprehensive guide on creating JavaScript applications, including a bank account object, merging customer and account data, a scientific calculator, a Tic Tac Toe game, and a palindrome checker. It includes code snippets for each application, demonstrating various JavaScript concepts such as objects, arrays, higher-order functions, and event handling. The document serves as a practical resource for learning JavaScript through hands-on projects.

Uploaded by

oopsitsmysteria
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

UNIT 1

Create a JS Object for Bank Account (w attributes like à customer name, account type,
balance, data of creation, bank name, branch name, pan card number). Using JS Object
keyword, try to perform following activities ➢ List down all the entries of the bank object ➢
Check the existence of a key ➢ If key found, get the value for the key

// Creating a Bank Account object

const bankAccount = {

customerName: "John Doe",

accountType: "Savings",

balance: 15000.75,

dateOfCreation: "2021-05-15",

bankName: "ABC Bank",

branchName: "Main Branch",

panCardNumber: "ABCDE1234F"

};

// 1. List down all the entries of the bank object

console.log("Bank Account Details:");

for (const key in bankAccount) {

if (bankAccount.hasOwnProperty(key)) {

console.log(`${key}: ${bankAccount[key]}`);

// 2. Check the existence of a key

const keyToCheck = "balance"; // Change this to check for different keys


if (keyToCheck in bankAccount) {

console.log(`Key "${keyToCheck}" exists in the bank account object.`);

// 3. If key found, get the value for the key

const value = bankAccount[keyToCheck];

console.log(`Value for "${keyToCheck}": ${value}`);

} else {

Console.log(`Key "${keyToCheck}" does not exist in the bank account object.`);

Spread Operator ➢ Merge Customer and Account Arrays ➢ Update the Customer Object
with the new values ➢ Develop a function that takes a Spread Argument and calculates total
balance

// Sample Customer and Account Arrays

const customers = [

{ id: 1, name: "John Doe", age: 30 },

{ id: 2, name: "Jane Smith", age: 25 }

];

const accounts = [

{ customerId: 1, accountType: "Savings", balance: 15000.75 },

{ customerId: 2, accountType: "Checking", balance: 5000.50 }

];

// 1. Merge Customer and Account Arrays

const mergedData = customers.map(customer => {

const account = accounts.find(acc => acc.customerId === customer.id);

return { ...customer, ...account }; // Merging customer and account data


});

console.log("Merged Customer and Account Data:");

console.log(mergedData);

// 2. Update the Customer Object with new values

const updatedCustomer = { id: 1, name: "John Doe", age: 31, email:


"[email protected]" }; // New values

const index = mergedData.findIndex(c => c.id === updatedCustomer.id);

if (index !== -1) {

mergedData[index] = { ...mergedData[index], ...updatedCustomer }; // Update the


customer object

console.log("Updated Merged Data:");

console.log(mergedData);

// 3. Develop a function that takes a Spread Argument and calculates total balance

function calculateTotalBalance(...balances) {

return balances.reduce((total, balance) => total + balance, 0);

// Example usage of the function

const totalBalance = calculateTotalBalance(

...accounts.map(account => account.balance) // Spread the balances from the accounts


array

);
console.log(`Total Balance: ${totalBalance}`);

UNIT 2

Create a list of Bank Objects (same kind of object you used in above lab, but in an array
format) ➢ Display the banks where balance is greater than 200 ➢ deduct 10% of the Bank
account balance, as part of monthly service fees ➢ Display the banks where balance is
greater than 200 and branch code is “Chennai” ➢ Add a new Bank to the given array ➢
Delete a bank from the array (use splice operator) ➢ Calculate the total balance of all bank
accounts

// Creating an array of Bank Account objects

const bankAccounts = [

customerName: "John Doe",

accountType: "Savings",

balance: 2500.75,

dateOfCreation: "2021-05-15",

bankName: "ABC Bank",

branchName: "Chennai",

panCardNumber: "ABCDE1234F"

},

customerName: "Jane Smith",

accountType: "Checking",

balance: 150.50,

dateOfCreation: "2020-03-10",

bankName: "XYZ Bank",

branchName: "Mumbai",
panCardNumber: "FGHIJ5678K"

},

customerName: "Alice Johnson",

accountType: "Savings",

balance: 3000.00,

dateOfCreation: "2019-07-20",

bankName: "LMN Bank",

branchName: "Chennai",

panCardNumber: "LMNOP9012Q"

},

customerName: "Bob Brown",

accountType: "Current",

balance: 500.00,

dateOfCreation: "2022-01-05",

bankName: "PQR Bank",

branchName: "Delhi",

panCardNumber: "RSTUV3456W"

];

// 1. Display the banks where balance is greater than 200

console.log("Banks with balance greater than 200:");

bankAccounts.forEach(account => {

if (account.balance > 200) {

console.log(account);

}
});

// 2. Deduct 10% of the Bank account balance as part of monthly service fees

bankAccounts.forEach(account => {

account.balance -= account.balance * 0.10; // Deducting 10%

});

// 3. Display the banks where balance is greater than 200 and branch code is “Chennai”

console.log("\nBanks with balance greater than 200 and branch code 'Chennai':");

bankAccounts.forEach(account => {

if (account.balance > 200 && account.branchName === "Chennai") {

console.log(account);

});

// 4. Add a new Bank to the given array

const newBankAccount = {

customerName: "Charlie Green",

accountType: "Savings",

balance: 1200.00,

dateOfCreation: "2023-02-10",

bankName: "STU Bank",

branchName: "Chennai",

panCardNumber: "XYZAB6789C"

};

bankAccounts.push(newBankAccount);

console.log("\nAdded new bank account:");


console.log(newBankAccount);

// 5. Delete a bank from the array (use splice operator)

const indexToDelete = bankAccounts.findIndex(account => account.customerName ===


"Jane Smith");

if (indexToDelete !== -1) {

const deletedAccount = bankAccounts.splice(indexToDelete, 1);

console.log("\nDeleted bank account:");

console.log(deletedAccount[0]);

// 6. Calculate the total balance of all bank accounts

const totalBalance = bankAccounts.reduce((total, account) => total + account.balance, 0);

console.log(`\nTotal balance of all bank accounts: ${totalBalance.toFixed(2)}`);

Develop a Scientific calculator that does following operations ➢ Rounded Value ➢ Area of
Circle ➢ Calculating of Sin, Cos and Tan functions ➢ Permiter of a Rectangle ➢ Employ
Arrow functions ➢ Employ HOC

// Higher-Order Function (HOC) to create a calculator operation

const createCalculator = (operation) => {

return (value1, value2) => {

return operation(value1, value2);


};

};

// Operations

const roundValue = (value) => Math.round(value);

const areaOfCircle = (radius) => Math.PI * Math.pow(radius, 2);

const perimeterOfRectangle = (length, width) => 2 * (length + width);

// Trigonometric functions

const sinFunction = (angle) => Math.sin(angle * (Math.PI / 180)); // Convert degrees to


radians

const cosFunction = (angle) => Math.cos(angle * (Math.PI / 180)); // Convert degrees to


radians

const tanFunction = (angle) => Math.tan(angle * (Math.PI / 180)); // Convert degrees to


radians

// Using HOC to create calculator functions

const roundCalculator = createCalculator((value) => roundValue(value));

const areaCalculator = createCalculator((radius) => areaOfCircle(radius));

const perimeterCalculator = createCalculator((length, width) =>


perimeterOfRectangle(length, width));

const sinCalculator = createCalculator((angle) => sinFunction(angle));

const cosCalculator = createCalculator((angle) => cosFunction(angle));

const tanCalculator = createCalculator((angle) => tanFunction(angle));

// Example usage

console.log("Rounded Value of 4.7:", roundCalculator(4.7)); // Rounded Value


console.log("Area of Circle with radius 5:", areaCalculator(5)); // Area of Circle

console.log("Perimeter of Rectangle (length: 10, width: 5):", perimeterCalculator(10, 5)); //


Perimeter of Rectangle

console.log("Sin of 30 degrees:", sinCalculator(30)); // Sin function

console.log("Cos of 60 degrees:", cosCalculator(60)); // Cos function

console.log("Tan of 45 degrees:", tanCalculator(45)); // Tan function

3) Develop a Tic Tac Toe game using ES6 JS. ❑Building a simple Tic Tac Toe game with
JavaScript is another excellent project idea you can finish in a single day. ❑You will create a
3×3 grid where two players will take turns marking the grid with cross and circle symbols.
The first player to get three marks in a horizontal, vertical, or diagonal row wins the game.
❑Although the game seems simple, you need to figure out how to create the logic that
follows the game rules in JavaScript. ❑Hence, before you start writing any code, break down
the flow of the game into logical steps first. ❑For a simple game like Tic Tac Toe, I find it
helpful to draw a small flow chart to visualize the different outcomes of the game. When I
can see the flow on paper, it’s easier to start writing actual code

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Tic Tac Toe</title>

<style>

body { font-family: Arial, sans-serif; }

.board { display: grid; grid-template-columns: repeat(3, 100px); gap: 5px; }

.cell { width: 100px; height: 100px; display: flex; align-items: center; justify-content:
center; font-size: 24px; border: 1px solid #000; cursor: pointer; }

.message { margin-top: 20px; }

</style>

</head>
<body>

<div class="board" id="board"></div>

<div class="message" id="message"></div>

<button id="reset">Reset Game</button>

<script>

class TicTacToe {

constructor() {

this.board = Array(9).fill(null);

this.currentPlayer = 'X';

this.isGameActive = true;

this.init();

init() {

this.renderBoard();

this.updateMessage();

document.getElementById('reset').addEventListener('click', () => this.resetGame());

renderBoard() {

const boardElement = document.getElementById('board');

boardElement.innerHTML = '';

this.board.forEach((cell, index) => {

const cellElement = document.createElement('div');

cellElement.classList.add('cell');

cellElement.textContent = cell;
cellElement.addEventListener('click', () => this.handleCellClick(index));

boardElement.appendChild(cellElement);

});

handleCellClick(index) {

if (this.board[index] || !this.isGameActive) return;

this.board[index] = this.currentPlayer;

if (this.checkWin()) {

this.updateMessage(`${this.currentPlayer} wins!`);

this.isGameActive = false;

} else if (this.board.every(cell => cell)) {

this.updateMessage("It's a draw!");

this.isGameActive = false;

} else {

this.currentPlayer = this.currentPlayer === 'X' ? 'O' : 'X';

this.updateMessage();

this.renderBoard();

checkWin() {

const winPatterns = [

[0, 1, 2], [3, 4, 5], [6, 7, 8], // rows

[0, 3, 6], [1, 4, 7], [2, 5, 8], // columns

[0, 4, 8], [2, 4, 6] // diagonals

];
return winPatterns.some(pattern => {

const [a, b, c] = pattern;

return this.board[a] && this.board[a] === this.board[b] && this.board[a] ===


this.board[c];

});

updateMessage(message = `${this.currentPlayer}'s turn`) {

document.getElementById('message').textContent = message;

resetGame() {

Develop a JavaScript palindrome checker. A palindrome is a phrase or a word that reads the
same backwards and forwards. Building a simple palindrome checker is great practice for
working with strings and manipulating them with JavaScript. Plus, checking for palindromes
can be a lot of fun!
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Palindrome Checker</title>

<style>

body { font-family: Arial, sans-serif; }

.container { margin: 20px; }

input { padding: 10px; width: 300px; }

button { padding: 10px; }

.result { margin-top: 20px; font-weight: bold; }

</style>

</head>

<body>

<div class="container">

<h1>Palindrome Checker</h1>

<input type="text" id="inputString" placeholder="Enter a word or phrase">

<button id="checkButton">Check Palindrome</button>

<div class="result" id="result"></div>

</div>

<script>

document.getElementById('checkButton').addEventListener('click', function() {

const inputString = document.getElementById('inputString').value;

const result = isPalindrome(inputString);

document.getElementById('result').textContent = result ?
`"${inputString}" is a palindrome!` :

`"${inputString}" is not a palindrome.`;

});

function isPalindrome(str) {

// Normalize the string: convert to lowercase and remove non-alphanumeric characters

const normalizedStr = str.toLowerCase().replace(/[^a-z0-9]/g, '');

// Reverse the normalized string

const reversedStr = normalizedStr.split('').reverse().join('');

// Check if the normalized string is equal to its reverse

return normalizedStr === reversedStr;

</script>

</body>

</html>

You might also like