0% found this document useful (0 votes)
135 views

Mean Stack Technologies Lab Record

MEAN STACK TECHNOLOGIES LAB MANUAL
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)
135 views

Mean Stack Technologies Lab Record

MEAN STACK TECHNOLOGIES LAB MANUAL
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/ 49

MEAN STACK TECHNOLOGIES

What is Mean stack?


A relatively new stack, MEAN stands for MongoDB, Express.js, AngularJS, and
Node.js. MEAN is an end-to-end JavaScript stack largely used for cloud-ready
applications. Understanding why you might use it, identifying examples of when to employ it, and
diving deeper into the individual components can help you maximize the value of MEAN for software
development.

Mean stack components


MongoDB
MongoDB is an open source, NoSQL database designed for cloud applications. It uses object- oriented
organization instead of a relational model.
In the MEAN stack, MongoDB stores the application’s data. Because both the application and the
database use JavaScript, there’s no need to translate the object as it journeys from the application to the
database and back. The application can push and pull objects between the back end and the database
without missing a beat.
Express
Express is a web application framework for Node.js. It balances ease of use and a full feature set.
Forming the backend of the MEAN stack, Express handles all the interactions between the frontend
and the database, ensuring a smooth transfer of data to the end user. It’s designed to be used with
Node.js and so continues the consistent use of JavaScript throughout the stack.
AngularJS
AngularJS—Google’s JavaScript frontend framework—isn’t the only frontend framework in use,
but it’s exceedingly popular. It is effectively the default for frontend JavaScript development.
If you’re developing a web application in JavaScript, you’re using AngularJS.
The MEAN stack includes AngularJS to help developers build the user-facing side of the
application. Because the backend, frontend and database are all built on JavaScript, there’s a smooth
flow of information between all parts of your application.
Node.js
Node.js is an open source JavaScript framework that uses asynchronous events to process multiple
connections simultaneously. It is an ideal framework for a cloud-based application, as it can
effortlessly scale requests on demand. You’re likely to find Node.js behind most well- known web
presence

pg. 1
HTML5 - The Language

Exercise - 1a:

Module name:

Case-insensitivity, Platform-independency, DOCTYPE Declaration, Types of Elements, HTML


Elements - Attributes, Metadata Element

Include the Metadata element in Homepage.html for providing description as "IEKart's is an


online shopping website that sells goods in retail. This company deals with various categories like
Electronics, Clothing, Accessories etc.

Problem Statement:

Consider the below code for Homepage.html.


Include the Metadata element for providing description as below:
Hussain's is an online shopping website that sells goods in retail. This company deals with
various
categories like Electronics, Clothing, Media, and so on...

Homepage.html:

<!DOCTYPE html>
<html>
<head>
<title>Hussain's Shopping</title>
</head>
<body>
</body>
</html>
Output:

pg. 2
HTML5 - The Language

Exercise - 1b: Module name: Sectioning Elements

Enhance the Homepage.html of IEKart's Shopping Application by adding appropriate


sectioning elements.

Problem Statement:

Consider the below code for Homepage.html. Enhance the semantics of content by adding
appropriate sectioning elements to achieve the below-mentioned expected output.

Homepage.html:

<!DOCTYPE html>
<html>

<head>
<title>Hussian's Shopping</title>
<meta name="keywords" content="Online, Shopping" />
</head>

<body>
Login | SignUp | Track order Welcome to Hussian's Shopping Clothing | Media
Hussain's very own one-stop solution for all your shopping needs !
Dont believe us? Click on the offers and check it out for yourself !! Clothing Media About
Us | Privacy Policy |Contact Us | FAQ | Terms & Conditions Copyright 2018 | Giri Like and
Connect with us
FB Twitter g+
</body>
</html>

Output:

pg. 3
HTML5 - The Language
Exercise – 1c:
Module na me: Paragraph Element, Division and Span Elements, List Element
Make use of appropriate grouping elements such as list items to "About Us" page of IEKart's
Shopping Application

Problem statement:

Consider below the "About Us" page of Hussain's Shopping Application.

Enhance the semantics of content by adding appropriate grouping elements such as list items in the
below-given code.

Aboutus.html:

<!DOCTYPE html>
<html>

<head>
<title>Hussian's Shopping</title>
<meta name="keywords" content="Online, Shopping" />
</head>

<body>
<header>
<nav> Login | SignUp | Track order </nav>
<h1> Welcome to Hussian's Shopping </h1>
<nav> Electronics | Books | Sports | Media | Clothing | Offers Zone
</nav>
</header>
<article>
<h2>About Us</h2> Hussain's Shopping is one among the world wide on-line products dealer.
<section> !--Include list items here--!</section>
</article>
<footer>
<nav> About Us | Privacy Policy | Contact Us | FAQ | Terms &
Conditions </nav> Copyright 2018 | Giri
</footer>
<aside> Like and Connect with us FB Twitter g+ </aside>
</body>

</html>

pg. 4
Output:

HTML5 - The Language

Exercise – 1d: Module name: Link Element


Link "Login", "SignUp" and "Track order" to "Login.html", "SignUp.html" and "Track.html"
page respectively. Bookmark each category to its details of IEKart's Shopping application.

Problem statement:

Consider the below Home Page of Hussain's Shopping Application.

Enhance semantics of content by adding the Link elements in the below-given code

Homepage.html.

Links to be added:

1.Link "Login", "SignUp" and "Track order" to "Login.html", "SignUp.html" and "Track.html" page
respectively.

2.Bookmark each category to its details.

Homepage.html

<!DOCTYPE html>
<html>
<head>
<meta name="keywords" content="Online, Shopping" />
<title>Hussain's Shopping</title>
</head>
<body>
<header>

pg. 5
<nav> Login | SignUp | Track order </nav>
<h1>Welcome to Hussain's Shopping</h1>
<nav> Clothing | Electronics </nav>
</header>
<article>
Hussain's one-stop solution for all your shopping needs ! Dont believe us? Click on the offers and
check it out for yourself !! <h2 id="Clothing"> Clothing </h2>
<h2 id="Electronics"> Electronics</h2>
</article>
<footer>
<nav> About Us | Privacy Policy | Contact Us | FAQ | Terms & Conditions </nav> Copyright
2016 | ETA UI and MarkUp
</footer>
<aside> Like and Connect with us FB Twitter g+ </aside>
</body>
</html>

Output:

HTML5 - The Language

Exercise – 1e: Module name: Character Entities


Add the © symbol in the Home page footer of IEKart's Shopping application.

Problem statement:

pg. 6
Consider below the Home page of Hussain's Shopping application. Modify the below code and
add the © symbol in the footer.

Homepage.html

<!DOCTYPE html>
<html>

<head>
<meta name="keywords" content="Online, Shopping" />
<title>Hussain's Shopping</title>
</head>

<body>
<header>
<nav>
<a href="Login.html"> Login </a> | <a href="Signup.html"> SignUp </a> |<a
href="TrackOrder.html"> Track order </a>
</nav>
<h1>Welcome to Hussain's Shopping</h1>
<nav>
<a href="#Clothing"> Clothing </a> | <a href="#Media"> Media </a>
</nav>
</header>
<article> Hussain & Co very own one-stop solution for all your shopping needs !
<br />
Dont believe us? Click on the offers
and check it out for yourself !!
<h2 id="Clothing"> Clothing </h2>
<h2 id="Media"> Media </h2>
</article>
<footer>
<nav> About Us | Privacy Policy | Contact Us | FAQ | Terms & Conditions </nav> Copyright
<!-- Add character entity for Copyright symbol -->2018 | Giri
</footer>
<aside> Like and Connect with us FB Twitter g+ </aside>
</body>

</html>

Output:

pg. 7
HTML5 - The Language
Exercise – 1f:

Module name:
HTML5 Global Attribute Add the global attributes such as contenteditable, spellcheck, id etc. to
enhance the Signup Page functionality of IEKart's Shopping application.

Problem statement:

Consider the Signup Page of Hussain's Shopping application. Enhance its functionality by adding
global attributes such as contenteditable and spellcheck to populate the below-given output.

Signup.html

<!DOCTYPE html>
<html>

<head>
<meta name="keywords" content="Online, Shopping" />
<title>Hussain's Shopping</title>
</head>
<body>
<header>
<h1>Sign Up!</h1>
</header>
<article>
<form action="success.html" method="get">
<table>
<tr>
<td><br><label for="username">Username:</label></td>
<td><br><input type="text" id="username" placeholder="Enter your username" required /></td>
</tr>
<tr>

pg. 8
<td><label for="email_id">Email ID:</label></td>
<td><input type="email" id="email_id" placeholder="Enter your email ID" required /></td>
</tr>
<tr>
<td><label for="password">Password:</label></td>
<td><input type="password" id="password" placeholder="Enter your password" required /></td>
</tr>
<tr>
<td><label for="gender">Gender:</label></td>
<td><label for="male">Male<input type="radio" id="male" name="gender" value="M"
/>&nbsp; <label for="female">Female<input
type="radio" id="female" name="gender" value="F" /></td>
</tr>
<tr>
<td><label for="dob">DOB:</label></td>
<td><input type="date" id="dob" required /></td>
</tr>
<tr>
<td><label for="phone_no">Phone number:</label></td>
<td><input type="text" id="phone_no" placeholder="Enter your contact number" pattern="+ [0-
9] {12}" required /></td>
</tr>
<tr>
<td><label for="country">Country:</label></td>
<td><select id="country" placeholder="Select your country">
<option value="India" />India
<option value="India" />USA
<option value="India" />UK
<option value="India" />Canada
<option value="India" />Belgium
<option value="India" />France </select></td>
</tr>
<tr>
<td><label id="language">Languages Known:</label></td>
<td><input type="checkbox" name="language" id="english" value="English"
checked="checked" /><label for="english">
English </label> <input type="checkbox" name="language" id="hindi" value="Hindi" /><label
for="hindi"> Hindi
</label> <input type="checkbox" name="language" id="french" value="French" /><label
for="french"> French </label></td>
</tr>
<tr>
<td><label for="pic">Profile pic:</label></td>
<td><input type="file" id="pic" required /></td>
</tr>
<tr>
<td><label for="yourself" dir="ltr">About yourself:</label></td>
<td><textarea></textarea></td> <!-- Add contenteditable and spellcheck
attribute -->
</tr>
<tr>

pg. 9
<td><input type="submit" value="Register" />
<td><input type="reset" value="Reset" />
</tr>
</table>
</form> <br /> <br /> <br /> <br />
</article>
<footer>
<nav> About Us | Privacy Policy | Contact Us | FAQ | Terms & Conditions </nav> Copyright
&copy; 2018 | Giri
</footer>
<aside> Like and Connect with us FB Twitter g+ </aside>
</body>

</html>

Output:

pg. 10
HTML5 - The Language

Exercise – 2a:

Module name:

Creating Table Elements, Table Elements : Colspan/Rowspan Attributes, border, cellspacing,


cellpadding attributes

Enhance the details page of IEKart's Shopping application by adding a table element to display the
available mobile/any inventories.

Problem statement:

Consider the Details page of Hussain's Shopping application. Enhance its functionality by adding a table
element to display the available mobile inventories to populate the below- given output.

Details.html

<!DOCTYPE html>
<html>
<head>
<meta name="keywords" content="Online, Shopping" />
<title>Hussain's Shopping</title>
</head>

<body>

<table border="1">
<caption>Mobile Inventories Available at Hussain's Shopping!</caption>
<!-- Design the table here -->
</table>
</body>
</html>

Output:

HTML5 - The Language

pg. 11
Exercise – 2b:

Module name: Creating Form Elements, Color and Date Pickers, Select and Datalist Elements
Using the form elements create Signup page for IEKart's Shopping application.

Problem statement:

Consider the below Signup page of Hussain's Shopping application.


Add the form elements in the below-given code to populate the output as below:

Signup.html

<!DOCTYPE html>
<html>

<head>
<meta name="keywords" content="Online, Shopping" />
<title>Hussian's Shopping</title>
</head>
<body>
<header>
<h1>Sign Up!</h1>
</header>
<article>
<!-- Add form here-->
<br /> <br /> <br /> <br />
</article>
<footer>
<nav> About Us | Privacy Policy | Contact Us | FAQ | Terms & Conditions </nav> Copyright
&copy; 2018 | Giri
</footer>
<aside> Like and Connect with us FB Twitter g+ </aside>
</body>
</html>

pg. 12
3. Javascript
a) Type of Identifiers
Write a JavaScript program to find the area of a circle using radius (var and
let -
reassign and observe the difference with var and let) and PI (const)

Program:

var radiusVar = 5;
let radiusLet = 7;
const PI = 3.14159;

// Calculate area using var


var areaVar = PI * radiusVar * radiusVar;
console.log("Area of circle with radius (var):", areaVar);

// Reassign radiusLet
radiusLet = 10;

// Calculate area using let


let areaLet = PI * radiusLet * radiusLet;
console.log("Area of circle with radius (let):", areaLet);

output:

Area of circle with radius (var): 78.53975


Area of circle with radius (let): 314.159

c) Operators and Types of Operators


Write JavaScript code to book movie tickets online and calculate the total price
considering the number of tickets and price per ticket as Rs. 150. Also, apply a festive
season discount of 10% and calculate the discounted amount.

Program:

const pricePerTicket = 150;


const festiveSeasonDiscount = 0.1;

// Function to calculate total price


function calculateTotalPrice(numTickets, pricePerTicket) {
return numTickets * pricePerTicket;
}

// Function to apply festive season discount

pg. 13
function applyDiscount(totalPrice, discountPercentage) {
return totalPrice - (totalPrice * discountPercentage);
}

// Number of tickets to book


const numTickets = 5; // Example: Booking 5 tickets

// Calculate total price without discount


const totalPriceWithoutDiscount = calculateTotalPrice(numTickets, pricePerTicket);

// Apply festive season discount


const discountedAmount = applyDiscount(totalPriceWithoutDiscount,
festiveSeasonDiscount);

// Display results
console.log(`Number of Tickets: ${numTickets}`);
console.log(`Price per Ticket: Rs. ${pricePerTicket}`);
console.log(`Total Price without Discount: Rs. ${totalPriceWithoutDiscount}`);
console.log(`Festive Season Discount (${festiveSeasonDiscount * 100}%): Rs. $
{totalPriceWithoutDiscount - discountedAmount}`);
console.log(`Total Price after Discount: Rs. ${discountedAmount}`);

output:

Number of Tickets: 5
Price per Ticket: Rs. 150
Total Price without Discount: Rs. 750
Festive Season Discount (10%): Rs. 75
Total Price after Discount: Rs. 675

d) Types of Statements, Non - Conditional Statements, Types of Conditional Statements, if


Statements, switch Statements
Write a JavaScript code to book movie tickets online and calculate the total
price based on the 3 conditions: (a) If seats to be booked are not more than 2, the cost
per
ticket remains Rs. 150. (b) If seats are 6 or more, booking is not allowed.

Program:

const pricePerTicket = 150;


const maxSeatsAllowed = 5;

// Function to calculate total price


function calculateTotalPrice(numTickets, pricePerTicket) {
return numTickets * pricePerTicket;
}

pg. 14
// Function to book movie tickets
function bookTickets(numTickets) {
if (numTickets <= 0) {
return "Please enter a valid number of tickets to book.";
} else if (numTickets <= 2) {
return calculateTotalPrice(numTickets, pricePerTicket);
} else if (numTickets > maxSeatsAllowed) {
return "Booking not allowed. Maximum seats allowed for booking is 5.";
} else {
return "Booking not allowed for the given number of tickets.";
}
}

// Example usage
const numTicketsToBook = 3; // Example: Booking 3 tickets
const totalPrice = bookTickets(numTicketsToBook);

// Display result
console.log(`Number of Tickets to Book: ${numTicketsToBook}`);
console.log(`Total Price: Rs. ${totalPrice}`);

const numTicketsToBook1 = 2; // Example: Booking 3 tickets


const totalPrice1 = bookTickets(numTicketsToBook1);

// Display result
console.log(`Number of Tickets to Book: ${numTicketsToBook1}`);
console.log(`Total Price: Rs. ${totalPrice1}`);

output:

Number of Tickets to Book: 3


Total Price: Rs. Booking not allowed for the given number of tickets.
Number of Tickets to Book: 2
Total Price: Rs. 300

pg. 15
4. Javascript

a) Working With Classes, Creating and Inheriting Classes


Create an Employee class extending from a base class Person. Hints: (i) Create a
class Person with name and age as attributes. (ii) Add a constructor to initialize the
values (iii) Create a class Employee extending Person with additional attributes role

Program:

// Base class: Person


class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}

// Derived class: Employee


class Employee extends Person {
constructor(name, age, role) {
super(name, age); // Call the constructor of the base class
this.role = role;
}
}

// Example usage:
const person1 = new Person("John", 30);
console.log("Person:", person1);

const employee1 = new Employee("Alice", 25, "Software Engineer");


console.log("Employee:", employee1);

Output:

Person: Person { name: 'John', age: 30 }


Employee: Employee { name: 'Alice', age: 25, role: 'Software Engineer' }

pg. 16
b) Working with Objects, Types of Objects, Creating Objects, Combining and cloning
Objects using Spread operator, Destructuring Objects, Browser Object Model, Document
Object Model
If a user clicks on the given link, they should see an empty cone, a different heading,
and a different message and a different background color. If user clicks again, they should
see a re-filled cone, a different heading, a different message

Program:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Click to See Cone</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="container">
<h1 id="heading">Click to See Cone</h1>
<p id="message">Click the button to reveal the cone!</p>
<button id="revealButton" onclick="toggleCone()">Reveal Cone</button>
<div id="cone"></div>
</div>

<script src="script.js"></script>
</body>
</html>

Styles.css:

body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
}

#container {
text-align: center;
margin-top: 50px;
}

#cone {
width: 200px;
height: 200px;
border-radius: 50%;
border: 2px solid #333;
background-color: transparent;
margin: 20px auto;
}

pg. 17
.hidden {
display: none;
}

.filled {
background-color: #ffc107;
}

Script.js:

let isConeFilled = false;

function toggleCone() {
const cone = document.getElementById('cone');
const heading = document.getElementById('heading');
const message = document.getElementById('message');

// Toggle cone filled/empty


if (isConeFilled) {
cone.classList.remove('filled');
message.textContent = 'Click the button to reveal the cone!';
} else {
cone.classList.add('filled');
message.textContent = 'You revealed the cone!';
}

// Toggle heading text


heading.textContent = isConeFilled ? 'Empty Cone' : 'Filled Cone';

// Toggle background color


document.body.style.backgroundColor = isConeFilled ? '#f0f0f0' : '#c0c0c0';

isConeFilled = !isConeFilled;
}

pg. 18
5. Javascript

a) Creating Arrays, Destructuring Arrays, Accessing Arrays, Array Methods

Create an array of objects having movie details. The object should include the movie
name, starring, language, and ratings. Render the details of movies on the page using the
array

Program:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Movies</title>
</head>
<body>
<div id="moviesContainer"></div>

<script src="script.js"></script>
</body>
</html>

JavaScript (script.js):

// Array of movie objects


const movies = [
{
name: "Inception",
starring: ["Leonardo DiCaprio", "Joseph Gordon-Levitt", "Ellen Page"],
language: "English",
ratings: {
IMDb: 8.8,
RottenTomatoes: 86,
Metacritic: 74
}
},
{
name: "The Shawshank Redemption",
starring: ["Tim Robbins", "Morgan Freeman", "Bob Gunton"],
language: "English",
ratings: {
IMDb: 9.3,
RottenTomatoes: 91,
Metacritic: 80
}
},

pg. 19
// Add more movie objects as needed
];

// Function to render movie details on the page


function renderMovies(movies) {
const moviesContainer = document.getElementById("moviesContainer");

movies.forEach(movie => {
const movieDiv = document.createElement("div");
movieDiv.innerHTML = `
<h2>${movie.name}</h2>
<p><strong>Starring:</strong> ${movie.starring.join(", ")}</p>
<p><strong>Language:</strong> ${movie.language}</p>
<p><strong>Ratings:</strong></p>
<ul>
<li>IMDb: ${movie.ratings.IMDb}</li>
<li>Rotten Tomatoes: ${movie.ratings.RottenTomatoes}</li>
<li>Metacritic: ${movie.ratings.Metacritic}</li>
</ul>
`;
moviesContainer.appendChild(movieDiv);
});
}

// Call the function to render movies


renderMovies(movies);

output:

pg. 20
b) Introduction to Asynchronous Programming, Callbacks, Promises, Async and Await,
Executing Network Requests using Fetch API
Simulate a periodic stock price change and display on the console. Hints: (i) Create
a method which returns a random number - use Math.random, floor and other methods
to return a rounded value. (ii) Invoke the method for every three seconds and stop

Program:

function generateRandomPriceChange() {
const priceChange = Math.floor(Math.random() * 11) - 5;
return priceChange;
}

// Function to simulate periodic stock price changes


function simulateStockPriceChange() {
// Initial stock price
let stockPrice = 100; // Starting price

// Display initial stock price


console.log("Initial Stock Price:", stockPrice);

// Function to update stock price and display


function updateStockPrice() {
const priceChange = generateRandomPriceChange();
stockPrice += priceChange;
console.log("Stock Price Change:", priceChange, "New Price:", stockPrice);
}

// Call the function to update stock price every three seconds


const intervalId = setInterval(updateStockPrice, 3000);

// Stop updating after 30 seconds (for demonstration)


setTimeout(() => {
clearInterval(intervalId);
console.log("Simulation stopped after 30 seconds.");
}, 30000); // Stop after 30 seconds (10000 ms)
}

// Start simulating stock price change


simulateStockPriceChange();

output:

Initial Stock Price: 100


Stock Price Change: 1 New Price: 101
Stock Price Change: -5 New Price: 96
Stock Price Change: 1 New Price: 97
Stock Price Change: -1 New Price: 96
Stock Price Change: 0 New Price: 96

pg. 21
Stock Price Change: 1 New Price: 97
Stock Price Change: 0 New Price: 97
Stock Price Change: 2 New Price: 99
Stock Price Change: 3 New Price: 102
Simulation stopped after 30 seconds.

c) Creating Modules, Consuming Modules


Validate the user by creating a login module. Hints: (i) Create a file login.js with a User
class. (ii) Create a validate method with username and password as arguments. (iii) If the username
and password are equal it will return "Login Successful"

Program:

login.js

class User {
constructor(username, password) {
this.username = username;
this.password = password;
}

validate(username, password) {
if (username === this.username && password === this.password) {
return "Login Successful";
} else {
return "Invalid username or password";
}
}
}

module.exports = User;

main.js

const User = require('./login');

// Create a user object with a username and password


const user = new User("exampleuser", "examplepassword");

// Validate the user


const result = user.validate("exampleuser", "examplepassword");

// Display the result


console.log(result);

Output:

Login Successful

pg. 22
6. Node.js

a) How to use Node.js

Verify how to execute different functions successfully in the Node.js platform.

To execute different functions successfully in the Node.js platform, you typically follow these steps:

 Install Node.js: First, ensure you have Node.js installed on your system. You can download and
install it from the official website: Node.js Download.
 Create a JavaScript file: Create a .js file where you will write your Node.js code. You can use any
text editor or an Integrated Development Environment (IDE) for this purpose.
 Write your functions: Define your functions within the JavaScript file. Here's an example:

myFunctions.js

function add(a, b) {
return a + b;
}

// Function to subtract two numbers


function subtract(a, b) {
return a - b;
}

Export functions: If you want to use these functions in another file, you need to export them. In Node.js,
you can use module.exports or exports object for this purpose. For example:

myFunctions.js

function add(a, b) {
return a + b;
}

function subtract(a, b) {
return a - b;
}

module.exports = {
add,
subtract
};
Import functions (optional): If you want to use these functions in another file, you need to import them
using require. For example:

pg. 23
index.js

const { add, subtract } = require('./myFunctions');

console.log(add(5, 3)); // Output: 8


console.log(subtract(5, 3)); // Output: 2

Run your file: To execute your Node.js script, open your terminal or command prompt, navigate to the
directory containing your JavaScript file, and run node filename.js, replacing filename.js with the name of
your JavaScript file.
node index.js

b) Create a web server in Node.js


Write a program to show the workflow of JavaScript code executable by creating web
server in Node.js

Program:
// Import required modules
const http = require('http');

// Define the hostname and port


const hostname = '127.0.0.1';
const port = 3000;

// Create the HTTP server


const server = http.createServer((req, res) => {
// Set the response header with status code 200 and content type
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');

// Write a simple JavaScript code snippet as the response


res.end(`
// Define a function to add two numbers
function add(a, b) {
return a + b;
}

// Call the add function with parameters 5 and 3


const result = add(5, 3);

// Output the result to the console


console.log("Result of addition:", result);
`);
});

// Start the server to listen for incoming connections


server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});

To run this program, save it in a file (e.g., server.js) and execute it using Node.js:

pg. 24
node server.js

c) Modular programming in Node.js


Write a Node.js module to show the workflow of Modularization of Node application
Let's say we have two modules:

 math.js: This module contains functions for basic mathematical operations.


 app.js: This is the main file where we import and use functions from the math.js module.

math.js

// Function to add two numbers


function add(a, b) {
return a + b;
}

// Function to subtract two numbers


function subtract(a, b) {
return a - b;
}

// Export the functions to make them accessible to other modules


module.exports = {
add,
subtract
};

app.js

// Import the math module


const math = require('./math');

// Use the functions from the math module


const resultAddition = math.add(5, 3);
const resultSubtraction = math.subtract(5, 3);

// Output the results


console.log("Result of addition:", resultAddition);
console.log("Result of subtraction:", resultSubtraction);

To run this application, ensure that math.js and app.js are in the same directory, and execute app.js using
Node.js:
node app.js

Output:
Result of addition: 8
Result of subtraction: 2

d) Restarting Node Application


Write a program to show the workflow of restarting a Node application.

pg. 25
Here's how you can set up a simple Node.js application with nodemon:
Install nodemon: First, install nodemon globally on your system using npm:
npm install -g nodemon

Create your Node.js application: Create a simple Node.js application. For this example, let's create a file
named app.js:

app.js

// Simple HTTP server


const http = require('http');

const hostname = '127.0.0.1';


const port = 3000;

const server = http.createServer((req, res) => {


res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});

server.listen(port, hostname, () => {


console.log(`Server running at http://${hostname}:${port}/`);
});

 Run the application with nodemon: Instead of running your Node.js application directly, you'll
run it with nodemon:
 Test the application: Visit http://127.0.0.1:3000/ in your web browser, and you should see "Hello,
World!" displayed.
 Modify the application: Now, let's make a change to our application. For example, change the
text to "Hello, Nodemon!" in the app.js file.
 Observe automatic restart: Once you save the changes, nodemon will detect the file change and
automatically restart your Node.js application. You'll see the console output indicating that the
server has restarted.

e) File Operations
Create a text file src.txt and add the following data to it. Mongo, Express, Angular, Node.

const fs = require('fs');

// Data to write to the file


const data = 'Mongo, Express, Angular, Node.';

// File path
const filePath = 'src.txt';

// Write data to the file


fs.writeFile(filePath, data, (err) => {
if (err) {
console.error('Error writing to file:', err);
} else {

pg. 26
console.log('Data has been written to src.txt');
}
});

7. Express.js

pg. 27
a) Defining a route, Handling Routes, Route Parameters, Query Parameters

// routes/routes.js

const express = require('express');


const router = express.Router();

// Define routes
router.get('/', (req, res) => {
res.send('Welcome to AdventureTrails!');
});

router.get('/about', (req, res) => {


res.send('About AdventureTrails');
});

router.get('/contact', (req, res) => {


res.send('Contact AdventureTrails');
});

// Export the router


module.exports = router;

// app.js (or server.js)

const express = require('express');


const app = express();

// Import routes
const routes = require('./routes/routes');

// Use routes
app.use('/', routes);

// Start the server


const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

b) How Middleware works, Chaining of Middlewares, Types of Middlewares

pg. 28
In myNotes application: (i) we want to handle POST submissions. (ii) display customized
error messages. (iii) perform logging.

app.use(middleware1);
app.use(middleware2);
app.use(middleware3);

// Middleware for handling POST submissions


app.use(express.urlencoded({ extended: true }));

// Middleware for displaying customized error messages


app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});

// Middleware for logging


app.use((req, res, next) => {
console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);
next();
});

const express = require('express');


const app = express();

// Middleware for handling POST submissions


app.use(express.urlencoded({ extended: true }));

// Middleware for displaying customized error messages


app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});

// Middleware for performing logging


app.use((req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next();
});

// Routes and other application logic...

// Start the server


const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

c) Connecting to MongoDB with Mongoose, Validation Types and Defaults

pg. 29
Write a Mongoose schema to connect with MongoDB

Install Mongoose in your project:


npm install mongoose

// Import Mongoose
const mongoose = require('mongoose');

// Define your schema


const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true
},
email: {
type: String,
required: true,
unique: true,
validate: {
validator: (value) => {
// Validate email format
return /\S+@\S+\.\S+/.test(value);
},
message: 'Invalid email format'
}
},
age: {
type: Number,
default: 18, // Default value
min: 18 // Minimum value
},
createdAt: {
type: Date,
default: Date.now // Default value set to current date/time
}
});

// Create a Mongoose model


const User = mongoose.model('User', userSchema);

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/myDatabase', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('Connected to MongoDB');
}).catch((err) => {
console.error('Error connecting to MongoDB:', err);
});

pg. 30
d) Models
Write a program to wrap the Schema into a Model object.

// Import Mongoose
const mongoose = require('mongoose');

// Define your schema


const carSchema = new mongoose.Schema({
brand: {
type: String,
required: true
},
model: {
type: String,
required: true
},
year: {
type: Number,
required: true
},
price: {
type: Number,
required: true
}
});

// Create a Mongoose model


const Car = mongoose.model('Car', carSchema);

// Example usage
const myCar = new Car({
brand: 'Toyota',
model: 'Corolla',
year: 2020,
price: 20000
});

// Save the car to the database


myCar.save()
.then((car) => {
console.log('Car saved successfully:', car);
})
.catch((error) => {
console.error('Error saving car:', error);
});

// Export the Car model


module.exports = Car;

8. Express.js

pg. 31
a) CRUD Operations
Write a program to perform various CRUD (Create-Read-Update-Delete) operations using
Mongoose library functions.

const express = require('express');


const mongoose = require('mongoose');

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/myDatabase', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('Connected to MongoDB');
}).catch((err) => {
console.error('Error connecting to MongoDB:', err);
});

// Define a Mongoose schema


const bookSchema = new mongoose.Schema({
title: String,
author: String,
pages: Number
});

// Create a Mongoose model


const Book = mongoose.model('Book', bookSchema);

// Create an Express app


const app = express();
app.use(express.json());

// Routes for CRUD operations


// Create a book
app.post('/books', async (req, res) => {
try {
const { title, author, pages } = req.body;
const book = new Book({ title, author, pages });
const savedBook = await book.save();
res.json(savedBook);
} catch (error) {
res.status(400).json({ message: error.message });
}
});

// Read all books


app.get('/books', async (req, res) => {
try {
const books = await Book.find();
res.json(books);
} catch (error) {
res.status(500).json({ message: error.message });

pg. 32
}
});

// Read a single book by ID


app.get('/books/:id', async (req, res) => {
try {
const book = await Book.findById(req.params.id);
if (!book) {
return res.status(404).json({ message: 'Book not found' });
}
res.json(book);
} catch (error) {
res.status(500).json({ message: error.message });
}
});

// Update a book by ID
app.put('/books/:id', async (req, res) => {
try {
const { title, author, pages } = req.body;
const updatedBook = await Book.findByIdAndUpdate(req.params.id, { title, author, pages },
{ new: true });
if (!updatedBook) {
return res.status(404).json({ message: 'Book not found' });
}
res.json(updatedBook);
} catch (error) {
res.status(400).json({ message: error.message });
}
});

// Delete a book by ID
app.delete('/books/:id', async (req, res) => {
try {
const deletedBook = await Book.findByIdAndDelete(req.params.id);
if (!deletedBook) {
return res.status(404).json({ message: 'Book not found' });
}
res.json({ message: 'Book deleted successfully' });
} catch (error) {
res.status(500).json({ message: error.message });
}
});

// Start the server


const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

b) API Development

pg. 33
In the myNotes application, include APIs based on the requirements provided. (i) API
should fetch the details of the notes based on a notesID which is provided in the URL. Test URL -
http://localhost:3000/notes/7555 (ii) API should update the details bas

const express = require('express');


const mongoose = require('mongoose');
const bodyParser = require('body-parser');

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/myNotesDB', { useNewUrlParser: true,
useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Error connecting to MongoDB:', err));

// Define Note schema


const noteSchema = new mongoose.Schema({
title: String,
content: String
});

// Create Note model


const Note = mongoose.model('Note', noteSchema);

// Create Express app


const app = express();

// Middleware for parsing JSON bodies


app.use(bodyParser.json());

// Fetch note by noteID


app.get('/notes/:noteID', async (req, res) => {
try {
const note = await Note.findById(req.params.noteID);
if (!note) {
return res.status(404).json({ message: 'Note not found' });
}
res.json(note);
} catch (error) {
res.status(500).json({ message: error.message });
}
});

// Update note by noteID


app.put('/notes/:noteID', async (req, res) => {
try {
const { title, content } = req.body;
const updatedNote = await Note.findByIdAndUpdate(req.params.noteID, { title, content }, {
new: true });
if (!updatedNote) {
return res.status(404).json({ message: 'Note not found' });
}

pg. 34
res.json(updatedNote);
} catch (error) {
res.status(400).json({ message: error.message });
}
});

// Start the server


const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

c) Why Session management, Cookies


Write a program to explain session management using cookies

First, install the express-session package:


npm install express-session

const express = require('express');


const session = require('express-session');

// Create Express app


const app = express();

// Middleware for session management


app.use(session({
secret: 'your_secret_key', // Secret key used for signing session ID cookie
resave: false, // Don't save session if unmodified
saveUninitialized: false, // Don't create session until something stored
cookie: {
maxAge: 1000 * 60 * 60 * 24 // Session cookie expires in 1 day (adjust as needed)
}
}));

// Route for setting session data


app.get('/setSession', (req, res) => {
req.session.username = 'user123'; // Set session data
res.send('Session data set successfully');
});

// Route for getting session data


app.get('/getSession', (req, res) => {
const username = req.session.username; // Get session data
if (username) {
res.send(`Session username: ${username}`);
} else {
res.send('Session data not found');
}
});

// Route for destroying session

pg. 35
app.get('/destroySession', (req, res) => {
req.session.destroy((err) => {
if (err) {
console.error('Error destroying session:', err);
res.send('Error destroying session');
} else {
res.send('Session destroyed successfully');
}
});
});

// Start the server


const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

d) Sessions
Write a program to explain session management using sessions.

First, install the express-session package:


npm install express-session

const express = require('express');


const session = require('express-session');

// Create Express app


const app = express();

// Middleware for session management


app.use(session({
secret: 'your_secret_key', // Secret key used for signing session ID cookie
resave: false, // Don't save session if unmodified
saveUninitialized: false // Don't create session until something stored
}));

// Route for setting session data


app.get('/setSession', (req, res) => {
req.session.username = 'user123'; // Set session data
res.send('Session data set successfully');
});

// Route for getting session data


app.get('/getSession', (req, res) => {
const username = req.session.username; // Get session data
if (username) {
res.send(`Session username: ${username}`);
} else {
res.send('Session data not found');
}

pg. 36
});

// Route for destroying session


app.get('/destroySession', (req, res) => {
req.session.destroy((err) => {
if (err) {
console.error('Error destroying session:', err);
res.send('Error destroying session');
} else {
res.send('Session destroyed successfully');
}
});
});

// Start the server


const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

e) Why and What Security, Helmet Middleware


Implement security features in myNotes application

install the Helmet package:


npm install helmet
const express = require('express');
const helmet = require('helmet');

// Create Express app


const app = express();

// Use Helmet middleware


app.use(helmet());

// Define routes and other application logic...

9. Typescript

pg. 37
a) Basics of TypeScript
On the page, display the price of the mobile-based in three different colors. Instead of using
the number in our code, represent them by string values like GoldPlatinum, PinkGold,
SilverTitanium.

// Define an enum for mobile colors


enum MobileColor {
GoldPlatinum = 'Gold Platinum',
PinkGold = 'Pink Gold',
SilverTitanium = 'Silver Titanium'
}

// Define the price of the mobile


const mobilePrice = 1000; // Assume the price is $1000

// Display the price of the mobile in three different colors


console.log(`Price of the mobile in ${MobileColor.GoldPlatinum}: $${mobilePrice}`);
console.log(`Price of the mobile in ${MobileColor.PinkGold}: $${mobilePrice}`);
console.log(`Price of the mobile in ${MobileColor.SilverTitanium}: $${mobilePrice}`);

b) Function
Define an arrow function inside the event handler to filter the product array with the
selected product object using the productId received by the function. Pass the selected product
object to the next screen.

interface Product {
productId: number;
productName: string;
// Other properties
}

const products: Product[] = [


{ productId: 1, productName: 'Product 1' },
{ productId: 2, productName: 'Product 2' },
// Other products
];

function handleProductSelection(productId: number) {


// Filter the products array to find the selected product
const selectedProduct = products.find(product => product.productId === productId);

if (selectedProduct) {
// Pass the selected product object to the next screen
// Assuming you have a function to navigate to the next screen
navigateToNextScreen(selectedProduct);
} else {
console.error('Selected product not found');
}
}

// Arrow function inside the event handler

pg. 38
const handleButtonClick = (productId: number) => {
handleProductSelection(productId);
};

// Example usage: Call handleButtonClick when a button is clicked


const selectedProductId = 2; // Example selected product ID
handleButtonClick(selectedProductId);

c) Parameter Types and Return Types


Consider that developer needs to declare a function - getMobileByVendor which accepts
string as input parameter and returns the list of mobiles.
interface Mobile {
vendor: string;
model: string;
// Other properties
}

const mobiles: Mobile[] = [


{ vendor: 'Samsung', model: 'Galaxy S21' },
{ vendor: 'Apple', model: 'iPhone 12' },
// Other mobiles
];

function getMobileByVendor(vendorName: string): Mobile[] {


// Filter the mobiles array to find mobiles by the given vendor name
const mobilesByVendor = mobiles.filter(mobile => mobile.vendor === vendorName);
return mobilesByVendor;
}

// Example usage
const samsungMobiles = getMobileByVendor('Samsung');
console.log('Samsung Mobiles:', samsungMobiles);

const appleMobiles = getMobileByVendor('Apple');


console.log('Apple Mobiles:', appleMobiles);

d) Arrow Function
Consider that developer needs to declare a manufacturer's array holding 4 objects
with id and price as a parameter and needs to implement an arrow function - myfunction
to populate the id parameter of manufacturers array whose price is greater than or equal

interface Manufacturer {
id: number;
price: number;
}

const manufacturers: Manufacturer[] = [


{ id: 1, price: 100 },
{ id: 2, price: 200 },
{ id: 3, price: 300 },

pg. 39
{ id: 4, price: 400 }
];

const myFunction = (priceThreshold: number): number[] => {


return manufacturers
.filter(manufacturer => manufacturer.price >= priceThreshold)
.map(manufacturer => manufacturer.id);
};

// Example usage
const priceThreshold = 250;
const result = myFunction(priceThreshold);
console.log(`Manufacturer IDs with price greater than or equal to ${priceThreshold}:`, result);

e) Optional and Default Parameters


Declare a function - getMobileByManufacturer with two parameters namely
manufacturer and id, where manufacturer value should passed as Samsung and id parameter
should be optional while invoking the function, if id is passed as 101 then this function should
interface Mobile {
manufacturer: string;
model: string;
id: number;
}

const mobiles: Mobile[] = [


{ manufacturer: 'Samsung', model: 'Galaxy S20', id: 100 },
{ manufacturer: 'Samsung', model: 'Galaxy Note 20', id: 101 },
{ manufacturer: 'Apple', model: 'iPhone 12', id: 200 },
// Other mobiles
];

function getMobileByManufacturer(manufacturer: string, id?: number): Mobile | undefined {


let filteredMobiles = mobiles.filter(mobile => mobile.manufacturer === manufacturer);
if (id !== undefined) {
filteredMobiles = filteredMobiles.filter(mobile => mobile.id === id);
}
return filteredMobiles[0];
}

// Example usage
const manufacturer = 'Samsung';
const id = 101; // Optional parameter

const mobile = getMobileByManufacturer(manufacturer, id);


if (mobile) {
console.log(`Mobile found: ${mobile.manufacturer} ${mobile.model} (ID: ${mobile.id})`);
} else {
console.log('Mobile not found');
}
10. Typescript

pg. 40
a) Rest Parameter
Implement business logic for adding multiple Product values into a cart variable
which is type of string array.

// Define the cart variable as an array of strings


let cart: string[] = [];

// Function to add products to the cart


function addToCart(...products: string[]): void {
// Add each product to the cart array
products.forEach(product => {
cart.push(product);
});
}

// Example usage
addToCart('Product 1', 'Product 2', 'Product 3');
console.log('Cart:', cart); // Output: ['Product 1', 'Product 2', 'Product 3']

// You can add more products to the cart


addToCart('Product 4', 'Product 5');
console.log('Cart:', cart); // Output: ['Product 1', 'Product 2', 'Product 3', 'Product 4', 'Product 5']

b) Creating an Interface
Declare an interface named - Product with two properties like productId and
productName with a number and string datatype and need to implement logic to populate the
Product details.

// Declare an interface named Product


interface Product {
productId: number;
productName: string;
}

// Function to populate product details


function populateProductDetails(productId: number, productName: string): Product {
// Create a new product object
const product: Product = {
productId: productId,
productName: productName
};
return product;
}

// Example usage
const productId = 1;
const productName = 'Product 1';

pg. 41
// Populate product details
const productDetails = populateProductDetails(productId, productName);
console.log('Product Details:', productDetails);

c) Duck Typing
Declare an interface named - Product with two properties like productId and
productName with the number and string datatype and need to implement logic to
populate the Product details.

// Declare an interface named Product


interface Product {
productId: number;
productName: string;
}

// Function to populate product details


function populateProductDetails(productId: number, productName: string): Product {
// Create a new product object
const product: Product = {
productId: productId,
productName: productName
};
return product;
}

// Example usage
const productId: number = 123;
const productName: string = 'Example Product';

// Populate product details


const productDetails: Product = populateProductDetails(productId, productName);
console.log('Product Details:', productDetails);

d) Function Types
Declare an interface with function type and access its value.

// Declare an interface with a function type


interface MathOperation {
(x: number, y: number): number;
}

// Implement the interface


const add: MathOperation = (x, y) => {
return x + y;
};

const subtract: MathOperation = (x, y) => {


return x - y;
};

pg. 42
// Access the value of the implemented functions
console.log('Result of addition:', add(5, 3)); // Output: 8
console.log('Result of subtraction:', subtract(8, 3)); // Output: 5

11. Typescript

pg. 43
a) Extending Interfaces
Declare a productList interface which extends properties from two other declared
interfaces like Category,Product as well as implementation to create a variable of this
interface type

// Declare the Category interface


interface Category {
categoryId: number;
categoryName: string;
}

// Declare the Product interface


interface Product {
productId: number;
productName: string;
}

// Declare the ProductList interface which extends properties from Category and Product
interface ProductList extends Category, Product {}

// Create a variable of type ProductList


const productList: ProductList = {
categoryId: 1,
categoryName: 'Electronics',
productId: 101,
productName: 'Smartphone'
};

// Access the properties of the productList variable


console.log('Product List:', productList);

b) Classes
Consider the Mobile Cart application, Create objects of the Product class and place
them into the productlist array.

// Define the Product class


class Product {
constructor(public productId: number, public productName: string) {}
}

// Create objects of the Product class


const product1 = new Product(1, 'Mobile Phone 1');
const product2 = new Product(2, 'Mobile Phone 2');
const product3 = new Product(3, 'Mobile Phone 3');

// Place the products into the productlist array

pg. 44
const productList: Product[] = [product1, product2, product3];

// Log the productList array


console.log('Product List:', productList);

c) Constructor
Declare a class named - Product with the below-mentioned declarations: (i)
productId as number property (ii) Constructor to initialize this value (iii) getProductId
method to return the message "Product id is <<id value>>"

// Declare the Product class


class Product {
productId: number;

// Constructor to initialize the productId


constructor(productId: number) {
this.productId = productId;
}

// Method to get the productId


getProductId(): string {
return `Product id is ${this.productId}`;
}
}

// Example usage
const product = new Product(123);
console.log(product.getProductId());
Output: "Product id is 123"

d) Access Modifiers
Create a Product class with 4 properties namely productId, productName,
productPrice, productCategory with private, public, static, and protected access modifiers
and accessing them through Gadget class and its methods.

// Define the Product class


class Product {
// Define properties with different access modifiers
private productId: number;
public productName: string;
static productPrice: number;
protected productCategory: string;

// Constructor to initialize properties


constructor(productId: number, productName: string, productCategory: string) {

pg. 45
this.productId = productId;
this.productName = productName;
this.productCategory = productCategory;
}

// Method to get productId


getProductId(): number {
return this.productId;
}

// Static method to get productPrice


static getProductPrice(): number {
return Product.productPrice;
}
}

// Set static property value


Product.productPrice = 1000;

// Define the Gadget class


class Gadget extends Product {
// Constructor to call the base class constructor
constructor(productId: number, productName: string, productCategory: string) {
super(productId, productName, productCategory);
}

// Method to get productCategory


getProductCategory(): string {
// Accessing protected property from base class
return this.productCategory;
}
}

// Create an instance of Gadget class


const gadget = new Gadget(1, 'Smartphone', 'Electronics');
// Access properties and methods
console.log('Product Name:', gadget.productName);
console.log('Product ID:', gadget.getProductId());
console.log('Product Category:', gadget.getProductCategory());
console.log('Product Price:', Product.getProductPrice());

Output: "Smartphone"
1
“Electronics”
1000
12. Typescript
pg. 46
a) Properties and Methods
Create a Product class with 4 properties namely productId and methods to
setProductId() and getProductId().

// Define the Product class


class Product {
private productId: number;

// Method to set productId


setProductId(productId: number): void {
this.productId = productId;
}

// Method to get productId


getProductId(): number {
return this.productId;
}
}

// Create an instance of the Product class


const product = new Product();

// Set productId using the set method


product.setProductId(123);

// Get productId using the get method


console.log('Product ID:', product.getProductId());

Output: 123

b) Creating and using Namespaces


Create a namespace called ProductUtility and place the Product class definition in
it. Import the Product class inside productlist file and use it.

// Define the namespace ProductUtility


namespace ProductUtility {
// Define the Product class
export class Product {
private productId: number;

// Method to set productId


setProductId(productId: number): void {
this.productId = productId;
}

pg. 47
// Method to get productId
getProductId(): number {
return this.productId;
}
}
}

// Import the Product class from the ProductUtility namespace


import { ProductUtility } from './productUtility';

// Create an instance of the Product class


const product = new ProductUtility.Product();

// Set productId using the set method


product.setProductId(123);

// Get productId using the get method


console.log('Product ID:', product.getProductId());

Output: 123

c) Creating and using Modules


Consider the Mobile Cart application which is designed as part of the functions in
amodule to calculate the total price of the product using the quantity and price values and
assign it to a totalPrice variable.

// Define a module named MobileCart


module MobileCart {
// Function to calculate the total price of a product
export function calculateTotalPrice(quantity: number, price: number): number {
return quantity * price;
}
}

// Example usage
const quantity = 3;
const price = 100; // Assume the price of the product is $100

// Calculate the total price using the calculateTotalPrice function


const totalPrice = MobileCart.calculateTotalPrice(quantity, price);
console.log('Total Price:', totalPrice);

Output: 300

pg. 48
d) What is Generics, What are Type Parameters, Generic Functions, Generic Constraints
Create a generic array and function to sort numbers as well as string values.

// Define a generic function to sort an array of numbers or strings


function sortArray<T>(array: T[]): T[] {
// Check if the elements of the array are numbers or strings
if (typeof array[0] === 'number') {
// Sort the array of numbers
return array.sort((a, b) => <number>a - <number>b);
} else if (typeof array[0] === 'string') {
// Sort the array of strings
return array.sort();
} else {
// Unsupported type
throw new Error('Unsupported array type');
}
}

// Example usage with numbers


const numbers: number[] = [3, 1, 5, 2, 4];
console.log('Sorted numbers:', sortArray(numbers)); // Output: [1, 2, 3, 4, 5]

// Example usage with strings


const strings: string[] = ['banana', 'apple', 'orange', 'grape'];
console.log('Sorted strings:', sortArray(strings));

Output: ["apple", "banana", "grape", "orange"]

pg. 49

You might also like