Java Script
Java Script
===================================================================================
=========================
<button id="fade-btn">Fade</button>
<div id="fade-box" style="width: 100px; height: 100px; background-color: lightblue;
opacity: 1;"></div>
<script>
const selectors = {
btn: document.getElementById("fade-btn"),
box: document.getElementById("fade-box")
};
===================================================================================
================================
<button id="pulse-btn">Pulse</button>
<style>
#pulse-btn {
width: 100px;
height: 50px;
background-color: lightseagreen;
color: white;
border: none;
border-radius: 5px;
font-size: 16px;
position: relative;
}
</style>
<script>
const selectors = {
btn: document.getElementById("pulse-btn") // Fixed semicolon to comma
};
===================================================================================
=============================
const selectors = {
btn: document.getElementById("bounce-color-btn"), // Fixed ID
box: document.getElementById("bounce-color-box")
};
===============================================================================
<button id="rotate-btn">Start Rotation</button>
<div id="rotate-box" style="width: 100px; height: 100px; background-color:
lightpink; position: relative;"></div>
<script>
const selectors = {
btn: document.getElementById("rotate-btn"), // Fixed typo
box: document.getElementById("rotate-box")
};
===================================================================================
==========================
<button id="slide-btn">Start Slide</button>
<div id="slide-container" style="width: 400px; height: 100px; position: relative;
border: 2px solid black;">
<div id="slide-box" style="width: 50px; height: 50px; background-color:
lightblue; position: absolute; left: 0;"></div>
</div>
<script>
const selectors = {
btn: document.getElementById("slide-btn"),
container: document.getElementById("slide-container"),
box: document.getElementById("slide-box") // Corrected ID
};
// Change direction when the box reaches the edge of the container
if (position >= width - elementToAnimate.offsetWidth || position <= 0) {
direction *= -1; // Reverse direction
}
}, 10);
};
===================================================================================
=====================================
<button id="bounce-btn">Start Bounce</button>
<div id="bounce-container" style="width: 200px; height: 200px; position: relative;
border: 2px solid black; overflow: hidden;">
<div id="bounce-ball" style="width: 50px; height: 50px; background-color: orange;
border-radius: 50%; position: absolute; bottom: 0;"></div>
</div>
<script>
const selectors = {
btn: document.getElementById("bounce-btn"),
ball: document.getElementById("bounce-ball")
};
// Change direction when the ball hits the top or bottom of the container
if (position >= 150) { // Adjust based on the container size and ball size
direction = -1; // Start moving down
} else if (position <= 0) {
direction = 1; // Start moving up
}
}, 10);
};
===================================================================================
===============================
<button id="slide-up-btn">Slide Up</button>
<div id="slide-box" style="width: 100px; height: 100px; background-color:
lightgreen; position: absolute; bottom: 0;"></div>
<script>
const selectors = {
btn: document.getElementById("slide-up-btn"),
box: document.getElementById("slide-box")
};
===================================================================================
========================
<button id="fade-in-btn">Fade In Box</button>
<div id="fade-box" style="width: 100px; height: 100px; background-color:
lightcoral; opacity: 0;"></div>
<script>
const selectors = {
btn: document.getElementById("fade-in-btn"),
box: document.getElementById("fade-box")
};
===================================================================================
================================
<button id="animate-btn">Start Animation</button>
<div id="box" style="width: 100px; height: 100px; background-color: lightblue;
position: absolute; left: 0;"></div>
<script>
const box = document.getElementById("box");
const btn = document.getElementById("animate-btn");
===================================================================================
======
<!-- HTML -->
<div id="mouse-area" style="width: 100%; height: 300px; background-color:
lightblue;">
Hover over this area to see the mouse position.
</div>
<p id="mouse-position">Mouse position: </p>
===================================================================================
===========
<button id="single-click-btn">Single Click Me</button>
<button id="double-click-btn">Double Click Me</button>
<script>
const singleClickBtn = document.getElementById("single-click-btn");
const doubleClickBtn = document.getElementById("double-click-btn");
function handleSingleClick() {
singleClickBtn.addEventListener("click", () => {
alert("Single Click");
});
}
function handleDoubleClick() {
doubleClickBtn.addEventListener("dblclick", () => {
alert("Double Click");
});
}
handleSingleClick();
handleDoubleClick();
</script>
===================================================================================
=================
<form id="submit-form">
<label for="name">Enter your name:</label>
<input type="text" id="name-input" name="name">
<button type="submit">Submit</button>
</form>
<p id="message"></p>
<script>
function handleFormSubmition() {
const formToHandle = document.getElementById("submit-form");
const message = document.getElementById("message");
handleFormSubmition();
</script>
===================================================================================
<select id="color-select">
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
<p id="color-paragraph">This text will change color based on your selection.</p>
<script>
function changeTextColor() {
const select = document.getElementById("color-select");
const paragraph = document.getElementById("color-paragraph");
select.addEventListener("change", () => {
if (select.value === "red") {
paragraph.style.color = "red";
} else if (select.value === "blue") {
paragraph.style.color = "blue";
} else if (select.value === "green") {
paragraph.style.color = "green";
} else {
paragraph.style.color = "black";
}
});
}
changeTextColor();
</script>
===================================================================================
=======
<input type="text" id="text-input" placeholder="Focus on me">
<p id="text-paragraph">Watch the text color change!</p>
<script>
function toggleTextColor()
{
const input = document.getElementById("text-input");
const paragraph = document.getElementById("text-paragraph");
input.addEventListener("focus", () => {
paragraph.style.color = "green";
});
input.addEventListener("blur", () => {
paragraph.style.color = "black";
});
}
toggleTextColor();
</script>
===================================================================================
===========
<button id="toggle-paragraph-btn">Hover Over Me</button>
<p id="paragraph" style="display: block;">This paragraph will be hidden on
hover.</p>
<script>
function toggleVisibility()
{
const btn = document.getElementById("toggle-paragraph-btn");
const paragraph = document.getElementById("paragraph");
btn.addEventListener("mouseover", () => {
paragraph.style.display = "none"; // Corrected property name
});
btn.addEventListener("mouseout", () => {
paragraph.style.display = "block"; // Corrected property name
});
}
toggleVisibility();
</script>
===================================================================================
=======================
<button id="color-btn">Double-Click Me</button>
<div id="color-box" style="width: 100px; height: 100px; background-color:
lightblue;"></div>
<script>
function changeBackgroundColor() {
const btn = document.getElementById("color-btn");
const box = document.getElementById("color-box");
btn.addEventListener("dblclick", () => {
box.style.backgroundColor = "yellow"; // Corrected property name
});
}
changeBackgroundColor();
</script>
===================================================================================
======
<button id="change-text-btn">Click Me</button>
<p id="text-paragraph">Original Text</p>
<script>
function changeText()
{
const btn = document.getElementById("change-text-btn");
const paragraph = document.getElementById("text-paragraph");
btn.addEventListener("click", () => {
paragraph.textContent = "Altered Text";
});
}
changeText();
</script>
===================================================================================
=========
<form id="checkbox-form">
<input type="checkbox" id="agree-checkbox">
<label for="agree-checkbox">I agree to the terms and conditions</label>
<br>
<button type="button" id="check-status-btn">Check Status</button>
</form>
<p id="checkbox-status"></p>
button.addEventListener("click", () => {
if (checkbox.checked) {
statusDisplay.innerHTML = "Checkbox is checked!";
} else {
statusDisplay.innerHTML = "Checkbox is unchecked!";
}
});
}
handleCheckbox();
</script>
==================================================================================
<form id="form-value">
<input type="text" id="text-input" placeholder="Enter text">
<button type="button" id="display-value-btn">Display Value</button>
</form>
<p id="value-display"></p>
<script>
function handleForm() {
const formToHandle = document.getElementById("form-value");
const button = document.getElementById("display-value-btn");
const input = document.getElementById("text-input");
const paragraph = document.getElementById("value-display");
button.addEventListener("click", () => {
paragraph.innerHTML = input.value;
});
}
handleForm();
</script>
===================================================================================
==============
<button id="toggle-bg-btn">Toggle Background Color</button>
<div id="box" style="width: 100px; height: 100px; background-color:
lightblue;"></div>
<script>
function toggleBackgroundColor()
{
const btn = document.getElementById("toggle-bg-btn");
const element = document.getElementById("box");
btn.addEventListener("click", () => {
if(element.style.backgroundColor === "lightgreen")
{
element.style.backgroundColor = "lightblue";
}
else
{
element.style.backgroundColor = "lightgreen";
}
});
}
toggleBackgroundColor();
</script>
===================================================================================
================
<button id="btn">Hover Me</button>
<p>lorem ipsum doors highlight color</p>
<script>
function changeColor() {
const paragraph = document.querySelector("p");
const btn = document.getElementById("btn");
btn.addEventListener("mouseover", () => {
paragraph.style.color = "red";
});
btn.addEventListener("mouseout", () => {
paragraph.style.color = ""; // Resets to the default color
});
}
changeColor();
</script>
===================================================================================
=======================
<button id="btn"> Hove Me </button>
<p> lorem ipsum doors highlight color </p>
<script>
function changeColor()
{
const paragraph = document.querySelector("p");
const btn = document.getElementById("btn");
btn.addEventListener("mouseover", () => {
paragraph.style.color = "red";
});
}
changeColor();
</script>
===================================================================================
===========
===================================================================================
====
<button id="increase-font-btn">Increase Font Size</button>
<div id="text-container">
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
</div>
<script>
function changeFontSize() {
const paragraphs = document.getElementById("text-
container").getElementsByTagName("p");
const button = document.getElementById("increase-font-btn");
button.addEventListener("click", () => {
for (let i = 0; i < paragraphs.length; i++) {
let currentSize = window.getComputedStyle(paragraphs[i],
null).getPropertyValue('font-size');
let newSize = parseFloat(currentSize) + 2 + "px";
paragraphs[i].style.fontSize = newSize;
}
});
}
changeFontSize();
</script>
===================================================================================
========================
<!-- HTML -->
<button id="count-btn">Count Paragraphs</button>
<div id="paragraph-container">
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
</div>
<p id="paragraph-count">Paragraph count: </p>
<script>
function countParagraphs()
{
const button = document.getElementById("count-btn");
const container = document.getElementById("paragraph-container");
const result = document.getElementById("paragraph-count");
button.addEventListener("click", () => {
const count = container.getElementsByTagName("p").length;
result.innerHTML = "Paragraph count: " + count;
});
}
</script>
===================================================================================
=========================
<!-- HTML -->
<button id="change-text-btn">Change Text</button>
<p id="change-text">Original text.</p>
<script>
function changeText()
{
const button = document.getElementById("change-text-btn");
const paragraph = document.getElementById("change-text");
button.addEventListener("click", () => {
paragraph.innerHTML = "Text has been changed!";
})
}
changeText();
</script>
===================================================================================
=======================
<!-- HTML -->
<button id="toggle-btn">Toggle Highlight</button>
<p id="toggle-paragraph">This paragraph will be highlighted.</p>
===================================================================================
========================
<!-- HTML -->
<button id="remove-btn">Remove Last Paragraph</button>
<div id="container">
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<!-- Paragraphs will be removed from here -->
</div>
<script>
function removeParagraph() {
const container = document.getElementById("container");
const button = document.getElementById("remove-btn");
button.addEventListener("click", () => {
if (container.lastElementChild) {
container.removeChild(container.lastElementChild);
}
});
}
removeParagraph();
</script>
===================================================================================
===================
<!-- HTML -->
<button id="add-btn">Add Paragraph</button>
<div id="container">
<!-- New paragraphs will be added here -->
</div>
<script>
function addParagraph() {
const container = document.getElementById("container");
const button = document.getElementById("add-btn");
button.addEventListener("click", () => {
const newParagraph = document.createElement("p");
newParagraph.textContent = "New paragraph added";
container.appendChild(newParagraph);
});
}
addParagraph();
</script>
===================================================================================
=
<script>
function toggleVisibility() {
const elements = document.getElementsByClassName("toggle-item");
const button = document.getElementById("toggle-btn");
button.addEventListener("click", () => {
for (let i = 0; i < elements.length; i++) {
if (elements[i].style.display === "none") {
elements[i].style.display = "block";
} else {
elements[i].style.display = "none";
}
}
});
}
toggleVisibility();
</script>
===================================================================================
==
<script>
function changeBackgroundColor()
{
const elements = document.getElementsByClassName("hover-item");
for( let i = 0 ; i < elements.length ; i++)
{
elements[i].addEventListener("mouseover", () => {
elements[i].style.backgroundColor = "yellow";
})
}
}
changeBackgroundColor();
</script>
===================================================================================
===
<script>
function changeButtonText() {
const buttons = document.getElementsByClassName("btn");
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", () => {
buttons[i].textContent = "Clicked";
});
}
}
changeButtonText();
</script>
============================================================================
<script>
const items = document.getElementsByClassName("item");
for (let i = 0; i < items.length; i++) {
items[i].style.backgroundColor = "lightblue";
}
</script>
===================================================================================
=================
<script>
const header = document.getElementById("header");
header.innerHTML = "Welcome to My Website";
</script>
===================================================================================
=================
<!-- HTML -->
<button id="btn"> click me </button>
<div id="paragraphs">
<p> paragraph 1 </p>
<p> paragraph 2 </p>
<p> paragraph 3 </p>
</div>
===================================================================================
===============================
<!-- HTML -->
<button id="btn"> click me </button>
<div id="paragraphs">
<p> paragraph 1 </p>
<p> paragraph 2 </p>
<p> paragraph 3 </p>
</div>
================================================================================
// HTML
<button id="btn"> click me </button>
<p> paragraph 1 </p>
<p> paragraph 2 </p>
<p> paragraph 3 </p>
// JavaScript
<script>
function changeText()
{
const elements = document.querySelectorAll("p");
document.getElementById("btn").addEventListener("click", () => {
for (let i = 0 ; i < elements.length ; i++)
{
elements[i].innerHTML = "this text has been changed";
}
})
}
changeText();
</script>
===================================================================================
========================
<button id="btn"> Click to Disable </button>
<script>
const button = document.getElementById("btn");
button.addEventListener("click", () => {
button.disabled = true; // Boolean, not a string
});
</script>
===================================================================================
=======================
// HTML
<button id="btn"> click me </button>
<p> paragraph 1 </p>
<p> paragraph 2 </p>
<p> paragraph 3 </p>
// stylesheet CSS
.highlight {
background-color: yellow;
}
//JavaScript
<script>
function changeBackgroundColor()
{
const paragraph = document.querySelectorAll("p");
document.getElementById("btn").addEventListener("click", () => {
for (let i = 0 ; i < paragraph.length ; i++)
{
paragraph[i].classList.toggle("highlight");
}
})
}
changeBackgroundColor();
</script>
===================================================================================
========================
<script>
function imageVisibility()
{
const elements = document.querySelectorAll("img");
document.getElementById("btn").addEventListener("click", () => {
for (let i = 0 ; i < elements.length ; i++)
{
if (elements[i].style.display === "none")
{
elements[i].style.display = "block";
}
else
{
elements[i].style.display = "none";
}
}
})
}
imageVisibility();
</script>
===================================================================================
========
<button id="btn"> click me </button>
<script>
function changeBackgroundColor() {
let index = 0;
document.getElementById("btn").addEventListener("click", () => {
index += 1;
if (index === 1) {
document.body.style.backgroundColor = "red";
} else if (index === 2) {
document.body.style.backgroundColor = "green";
} else if (index === 3) {
document.body.style.backgroundColor = "blue";
index = 0; // Reset the index after reaching the last color
}
});
}
changeBackgroundColor();
</script>
===================================================================================
=============
<button id="btn"> click me </button>
<img id="img" src="./image.png" alt="" />
<script>
function imageVisibility() {
const image = document.getElementById("img");
document.getElementById("btn").addEventListener("click", () => {
if (image.style.display === "none") {
image.style.display = "block";
} else {
image.style.display = "none";
}
});
}
imageVisibility();
</script>
===================================================================================
=====================
<button id="btn"> click me </button>
<img id="image" src="./image1.png" alt="" />
<script>
function changeImage()
{
const image = document.getElementById("image");
document.getElementById("btn").addEventListener("click", () => {
image.src="./iamge2.png";
})
}
changeImage();
</script>
===================================================================================
======================
<button id="btn">Click me</button>
<ul id="list">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<li>item 4</li>
</ul>
<script>
function toggleListVisibility() {
const list = document.getElementById("list");
document.getElementById("btn").addEventListener("click", () => {
list.style.display = list.style.display === "none" ? "block" : "none";
});
}
toggleListVisibility();
</script>
===================================================================================
============
<button id="btn"> click me </button>
<ul>
<li> item 1 </li>
<li> item 2 </li>
<li> item 3 </li>
<li> item 4 </li>
</ul>
<script>
function listVisibility()
{
const list = document.querySelectorAll("li");
document.getElementById("btn").addEventListener("click", () => {
for (let i = 0 ; i < list.length ; i++)
{
if (list[i].style.display === "none")
{
list[i].style.display = "block";
}
else
{
list[i].style.display = "none";
}
}
});
}
listVisibility();
</script>
===================================================================================
=====================
// HTML
<button id="btn"> Click </button>
<p> pragraph 1 </p>
<p> pragraph 2 </p>
<p> pragraph 3 </p>
// stylesheet css
.paragraph {
color: red ;
}
//JavaScript
<script>
function changeColor()
{
const elements = document.querySelectorAll("p");
document.getElementById("btn").addEventListener("click", () => {
for (let i = 0 ; i < elements.length ; i++)
{
elements[i].classList.toggle("paragraph");
}
});
}
changeColor();
</script>
===================================================================================
============
<button id="btn"> click here </button>
<script>
function addClass() {
const elements = document.querySelectorAll("div");
document.getElementById("btn").addEventListener("click", () => {
for (let i = 0; i < elements.length; i++) {
elements[i].classList.add("highlight");
}
});
}
Make sure you define the `highlight` class in your CSS for the background color
change. Example:
```css
.highlight {
background-color: yellow;
}
```
Now the script should work as expected! Let me know if you're ready for the next
task.
===================================================================================
=================
<button id="btn"> click </button>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<script>
function changeColor() {
const elements = document.querySelectorAll("p"); // Selector "p" should be in
quotes
document.getElementById("btn").addEventListener("click", () => {
for (let i = 0; i < elements.length; i++) {
elements[i].style.color = "red"; // Color value should be in quotes
}
});
}
changeColor();
</script>
===================================================================================
===================
<button id="btn"> click here </button>
<p id="pa"> sdfsdf </p>
<script>
function changeFontSize()
{
const paragraph = document.getElementById("pa");
document.getElementById("btn").addEventListener("click" , () => {
paragraph.style.fontSize = "16px";
});
}
changeFontSize();
</script>
===================================================================================
=====================
<script>
function changeText() {
const paragraph = document.getElementById("paragraph");
// Correct the 'btn' reference by using quotes
document.getElementById("btn").addEventListener("click", () => {
paragraph.innerHTML = "Text has been changed";
});
}
===================================================================================
======================
<button id="btn">Click to append item</button>
<ul id="list"></ul>
<script>
const list = document.getElementById("list");
document.getElementById("btn").addEventListener("click", () => {
// Create a new list item
const newItem = document.createElement("li");
// Set the text content of the new item
newItem.textContent = "New Item";
// Append the new item to the list
list.append(newItem);
});
</script>
===================================================================================
===========
<button id="btn">Click me</button>
<p id="paragraph">Text is not hidden. Click the button to hide.</p>
<script>
function handleClick() {
const paragraph = document.getElementById("paragraph");
document.getElementById("btn").addEventListener("click", () => {
if (paragraph.style.display === "none") {
paragraph.style.display = "block";
} else {
paragraph.style.display = "none";
}
});
}
handleClick();
</script>
===================================================================================
=============
<p id="btn"> hover me </p>
<script>
const paragraph = document.getElementById("btn");
paragraph.addEventListener("mouseover" , () => {
paragraph.style.color = "red";
});
paragraph.addEventListener("mouseout" , () => {
paragraph.style.color = "blue";
})
</script>
===================================================================================
=======================
<button id="btn">button not hovered</button>
<script>
const btn = document.getElementById("btn");
btn.addEventListener("mouseover", () => {
btn.textContent = "button hovered";
});
btn.addEventListener("mouseout", () => {
btn.textContent = "button not hovered";
});
</script>
===================================================================================
============================
<button id="btn">Click me</button>
<p id="paragraph">fdsjk</p>
<script>
function handleClick() {
const paragraph = document.getElementById("paragraph");
document.getElementById("btn").addEventListener("click", () => {
if (paragraph.style.display === "block") {
paragraph.style.display = "none";
} else {
paragraph.style.display = "block";
}
});
}
===================================================================================
===================
<button id="btn"> click to change background color </button>
<script> document.getElementById("btn").addEventListener("click" , () => {
if (document.body.style.backgroundColor === "blue")
{
document.body.style.backgorundColor = "green";
}
else {
document.body.style.backgorundColor = "blue";
}
}) </script>
===================================================================================
====================
<button id="btn">Change Background</button>
<script>
document.getElementById("btn").addEventListener("click", () => {
document.body.style.backgroundColor = "red";
});
</script>
===================================================================================
=====
<button id="btn">Click Me!</button>
<script>
document.getElementById("btn").addEventListener('click', function() {
document.getElementById("btn").innerHTML = "Clicked!";
});
</script>
==============================================================================
document.queryselector('button').addEventListenner ('click', function(){
alert('Button Clicked');
})
==================================================================
function findLongestWord(S) {
if (S.length === 0) return ''; // Handle empty string case
return longestWord;
}
===================================================================================
=================
function removeDuplicates(S) {
let nonDuplicateArr = [];
for (let i = 0; i < S.length; i++) {
if (!nonDuplicateArr.includes(S[i])) {
nonDuplicateArr.push(S[i]);
}
}
return nonDuplicateArr.join(""); // Convert array back to string
}
===================================================================================
====================
function reverseString (S)
{
let reverseString = "";
for (let i = S.length - 1 ; i >= 0 ; i-- )
{
reverseString += S[i] ;
}
return reverseString ;
}
===================================================================================
======================
function capitalizeWords (S)
{
words = S.split(" ");
for (let i = 0 ; i < words.length ; i++ )
{
if (words[i][0] === words[i][0].toLowerCase())
{
words[i] = words[i][0].toUpperCase() + words[i].slice(1);
}
}
return words.join(" ");
}
===================================================================================
======================
function reverseString (S)
{
let reverseString = "";
for (let i = S.length - 1 ; i >= 0 ; i-- )
{
reverseString += S[i] ;
}
return reverseString ;
}
===================================================================================
========================
===================================================================================
=================
function calculatePrice(cart) {
let totalPrice = 0;
for (let i = 0; i < cart.length; i++) {
totalPrice += cart[i].price;
}
return totalPrice;
}
function calculateAveragePrice(cart) {
if (cart.length === 0) return 0; // Handle edge case where cart is empty
return calculatePrice(cart) / cart.length;
}
===================================================================================
======
function calculateDiscountedPrice(price, discountPercentage, quantity) {
===============================================================================
findItemBelowPrice (cart , maxPrice)
{
let itemsBelowPrice = [] ;
for (let i = 0 ; i < cart.length ; i++ )
{
if (cart[i].price < maxPrice)
{
itemsBelowPrice.push(cart[i]);
}
}
return itemsBelowPrice ;
}
===================================================================================
=====================
function findHighestPricedItem(cart) {
if (cart.length === 0) {
return null; // Handle the case where the cart is empty
}
===================================================================================
==================
function groupItemsByCategory(cart) {
// Create an empty object to hold the grouped items
const groupedItems = {};
return groupedItems;
}
// Example usage:
const cart = [
{ name: 'Item A', category: 'Electronics', price: 30 },
{ name: 'Item B', category: 'Clothing', price: 20 },
{ name: 'Item C', category: 'Electronics', price: 50 },
{ name: 'Item D', category: 'Clothing', price: 40 }
];
console.log(groupItemsByCategory(cart));
============================================
function sortCartByPrice(cart) {
// Sort cart array by price in ascending order
cart.sort((a, b) => a.price - b.price);
return cart;
}
===================================================================================
===================
function checkRange(price, minPrice, maxPrice) {
return (price >= minPrice && price <= maxPrice);
}
===================================================================================
==================
function findItemByName(cart, item) {
for (let i = 0; i < cart.length; i++) {
if (cart[i].name === item) {
return cart[i];
}
}
return null; // Return null if the item is not found
}
===================================================================================
====================
function getTotalPrice(cart) {
let totalPrice = 0;
for (let i = 0; i < cart.length; i++) {
totalPrice += cart[i].price * cart[i].quantity;
}
return totalPrice;
}
===================================================================================
=====
function getTotalItems(cart) {
let totalItems = 0;
for (let i = 0; i < cart.length; i++) {
totalItems += cart[i].quantity; // Summing up quantities
}
return totalItems;
}
===================================================================================
=======
===================================================================================
============
function removeItemFromCart(cart, item) {
const index = cart.findIndex(cartItem => cartItem.name === item);
if (index !== -1) {
cart.splice(index, 1); // Remove the item at the found index
return cart;
} else {
return "There's no item with that name.";
}
}
In the `splice()` method, the `1` represents the number of elements to remove from
the array starting at the specified index.
```javascript
cart.splice(index, 1);
```
If you wanted to remove more than one item (e.g., consecutive items), you could
increase the `1` to whatever number of items you'd like to remove.
===================================================================================
=========
if (existingItem) {
// If the item exists, increase its quantity
existingItem.quantity += quantity;
} else {
// If the item doesn't exist, add it to the cart
cart.push({ name: item, quantity: quantity });
}
return cart;
}
===================================================================================
=========
===================================================================================
==
function filterItemsByCategory(arr, category) {
let categoryArr = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i].category === category) {
categoryArr.push(arr[i]);
}
}
return categoryArr;
}
===================================================================================
// Function to add a new item to the todo list
function addTodoItem(todoList, item) {
todoList.push(item);
}
// Function to remove an item from the todo list by matching the text
function removeTodoItem(todoList, itemText) {
const index = todoList.findIndex(todo => todo.text === itemText);
if (index !== -1) {
todoList.splice(index, 1); // Remove the item if found
}
}
// Example usage
let todoList = [];
console.log(getTodoList(todoList));
// Output: [{ text: "Buy milk", completed: false }, { text: "Walk the dog",
completed: false }]
console.log(getTodoList(todoList));
// Output: [{ text: "Buy milk", completed: true }, { text: "Walk the dog",
completed: false }]
console.log(getTodoList(todoList));
// Output: [{ text: "Buy milk", completed: true }]
=================================================================================
function calculateOccurrence(arr, number) {
let numberOccurrence = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] === number) {
numberOccurrence += 1;
}
}
return numberOccurrence;
}
function findMostFrequentElement(arr) {
let frequencyMap = new Map();
return mostFrequentElement;
}
================================================================================
function calculateItemPrice(item) {
return item.price * item.quantity;
}
function calculateTotalPrice(cart) {
let totalPrice = 0;
for (let i = 0; i < cart.length; i++) {
totalPrice += calculateItemPrice(cart[i]);
}
return totalPrice;
}
===================================================================================
=====
function isOdd(number) {
return number % 2 !== 0; // Return true for odd numbers
}
function filterEvenNumbers(arr) {
let oddArr = [];
for (let i = 0; i < arr.length; i++) {
if (isOdd(arr[i])) {
oddArr.push(arr[i]);
}
}
return oddArr;
}
===================================================================================
==
function generateRandomNumber(min, max) {
let randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
return randomNumber;
}
===================================================================================
==========
function isValidURL(URL) {
// Check if the URL starts with http:// or https://
if (URL.startsWith("http://") || URL.startsWith("https://")) {
// Extract the part after the protocol
const domainAndPath = URL.split("://")[1];
===================================================================================
=========
function isValidEmail(email) {
// Check if the email contains exactly one '@'
let atSymbolIndex = email.indexOf('@');
if (atSymbolIndex === -1 || email.indexOf('@', atSymbolIndex + 1) !== -1) {
return false;
}
// Ensure that the domain extension (after the last dot) has at least 2
characters
let domainExtension = domainPart.substring(dotIndex + 1);
if (domainExtension.length < 2) {
return false;
}
return true;
}
===================================================================================
===============================
function checkCharactersLength(password) {
return password.length >= 8;
}
function checkLower(password) {
for (let i = 0; i < password.length; i++) {
if (password[i] === password[i].toLowerCase() && isNaN(password[i])) {
return true;
}
}
return false;
}
function checkUpper(password) {
for (let i = 0; i < password.length; i++) {
if (password[i] === password[i].toUpperCase() && isNaN(password[i])) {
return true;
}
}
return false;
}
function checkDigit(password) {
for (let i = 0; i < password.length; i++) {
if (!isNaN(password[i])) {
return true;
}
}
return false;
}
function checkSpecialChar(password) {
const specialChars = "!@#$%^&*";
for (let i = 0; i < password.length; i++) {
if (specialChars.includes(password[i])) {
return true;
}
}
return false;
}
function isStrongPassword(password) {
return (
checkCharactersLength(password) &&
checkLower(password) &&
checkUpper(password) &&
checkDigit(password) &&
checkSpecialChar(password)
);
}
// Test cases
console.log(isStrongPassword("Password123!")); // true
console.log(isStrongPassword("weakpass")); // false
===================================================================================
=====
function isPangram(str) {
// Convert the string to lowercase to handle case insensitivity
let lowerCaseStr = str.toLowerCase();
// Example usage
console.log(isPangram("The quick brown fox jumps over the lazy dog")); // true
console.log(isPangram("Hello World")); // false
===================================================================================
==============
function findMissingNumber(arr) {
let n = arr.length + 1; // There should be n numbers, but one is missing
let totalSum = (n * (n + 1)) / 2; // Sum of all numbers from 1 to n
let arrSum = 0;
for (let i = 0; i < arr.length; i++) {
arrSum += arr[i]; // Sum of elements in the array
}
===================================================================================
====================
function fibonacci(n) {
if (n === 0) {
return 0; // Base case for 0
}
if (n === 1) {
return 1; // Base case for 1
}
return fibonacci(n - 1) + fibonacci(n - 2); // Recursive case
}
===================================================================================
========
function sumDigits(number) {
let sumDigits = 0;
return sumDigits;
}
===================================================================================
=================
================================================================================
function flattenArray (arr)
{
return arr.flat(Infinity);
}
===============================================================================
function removesDuplicates (arr)
{
let uniqueArr = [];
for (let i = 0 ; i < arr.length ; i++)
{
if (!uniqueArr.includes(arr[i]))
{
unique.Arr.push(arr[i]);
}
}
return uniqueArr ;
}
=============================================================================
==========================================================================