Javascript Exercise
CallBack Functions:
- Write a function multiplyByTwo that takes a number as a parameter and returns the result of multiplying it by 2. Use a callback function to print the result.
function multiplyByTwo(number, callback) {
const result = number * 2;
callback(result);
}
function printResult(result) {
console.log("The result is:", result);
}
// Example usage
multiplyByTwo(5, printResult)
- Create an array of numbers. Write a function filterEvenNumbers that takes an array and a callback function as parameters. The callback function should return true if a number is even and false otherwise. Use the callback function to filter out the even numbers from the array and return a new array.
// N02
function filterEvenNumbers(array, callback) {
const filteredArray = [];
for (let i = 0; i < array.length; i++) {
if (callback(array[i])) {
filteredArray.push(array[i]);
}
}
return filteredArray;
}
function isEven(number) {
return number % 2 === 0;
}
// Example usage
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const filteredNumbers = filterEvenNumbers(numbers, isEven);
console.log(filteredNumbers); // Output: [2, 4, 6, 8, 10]
- Write a function calculatesum that takes two numbers and a callback function as parameters. The callback function should return the sum of the two numbers. Use the callback function to calculate the sum and print it
function calculateSum(num1, num2, callback) {
const sum = callback(num1, num2);
console.log("The sum is:", sum);
}
function calculateSumCallback(num1, num2) {
return num1 + num2;
}
// Example usage
calculateSum(5, 3, calculateSumCallback);
- Create an array of strings. Write a function convertToUpperCase that takes an array and a callback function as parameters. The callback function should convert each string in the array to uppercase and return the updated array. Use the callback function to convert the strings and print the updated array
function convertToUpperCase(array, callback) {
const updatedArray = [];
for (let i = 0; i < array.length; i++) {
const updatedString = callback(array[i]);
updatedArray.push(updatedString);
}
return updatedArray;
}
function toUpperCaseCallback(string) {
return string.toUpperCase();
}
// Example usage
const strings = ["hello", "world", "chinny"];
const updatedStrings = convertToUpperCase(strings, toUpperCaseCallback);
console.log(updatedStrings); // Output: ["HELLO", "WORLD", "OPENAI"]
- Write a function doMathOperation that takes two numbers and a callback function as parameters. The callback function should perform a mathematical operation (e.g., addition, subtraction, multiplication) on the two numbers and return the result. Use the callback function to perform different operations and print the results
function doMathOperation(num1, num2, callback) {
const result = callback(num1, num2);
console.log("The result is:", result);
}
function addition(num1, num2) {
return num1 + num2;
}
function subtraction(num1, num2) {
return num1 - num2;
}
function multiplication(num1, num2) {
return num1 * num2;
}
// Example usage
doMathOperation(5, 3, addition); // Output: The result is: 8
doMathOperation(5, 3, subtraction); // Output: The result is: 2
doMathOperation(5, 3, multiplication); // Output: The result is: 15
Promises:
- Write a function fetchData that returns a promise. The promise should resolve after a random delay (between 1 and 5 seconds) with a random number. Use setTimeout and the resolve function of the promise to accomplish this
function fetchData() {
return new Promise((resolve, reject) => {
const randomDelay = Math.floor(Math.random() * 5000) + 1000; // Random delay between 1 and 5 seconds
const randomNumber = Math.floor(Math.random() * 100); // Random number
setTimeout(() => {
resolve(randomNumber);
}, randomDelay);
});
}
// Example usage
fetchData()
.then((data) => {
console.log("Fetched data:", data);
})
.catch((error) => {
console.error("Error fetching data:", error);
});
- Create an array of URLs. Write a function fetchMultipleData that takes an array of URLs as a parameter and returns an array of promises. Each promise should fetch data from a corresponding URL. Use Promise.all to handle the array of promises and return the resolved data
Array of URLs
const urls = [
'https://api.example.com/data/1',
'https://api.example.com/data/2',
'https://api.example.com/data/3',
// Add more URLs here if needed
];
// Function to fetch data from each URL and return an array of promises
function fetchMultipleData(urls) {
const promises = urls.map(url =>
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.catch(error => {
console.error(`Error fetching data from ${url}: ${error.message}`);
return null;
})
);
return promises;
}
// Example usage
const dataPromises = fetchMultipleData(urls);
// Using Promise.all to handle the array of promises and get the resolved data
Promise.all(dataPromises)
.then(resolvedData => {
// The resolvedData array contains the data fetched from each URL
console.log(resolvedData);
})
.catch(error => {
console.error('Error while fetching data:', error);
});
- Write a function checkNumber that takes a number as a parameter and returns a promise. The promise should resolve if the number is even and reject with an error message if the number is odd. Use the resolve and reject functions of the promise to accomplish this
function checkNumber(number) {
return new Promise((resolve, reject) => {
if (number % 2 === 0) {
// Number is even, so resolve the promise
resolve(`${number} is an even number.`);
} else {
// Number is odd, so reject the promise with an error message
reject(new Error(`${number} is an odd number.`));
}
});
}
// Example usage
const numberToCheck = 7;
checkNumber(numberToCheck)
.then(result => {
console.log(result);
})
.catch(error => {
console.error(error.message);
});
- Create a function uploadFile that takes a file object and returns a promise. The promise should simulate uploading the file by resolving after a random delay (between 1 and 10 seconds) with a success message. Use setTimeout and the resolve function of the promise to accomplish this
function uploadFile(file) {
return new Promise((resolve, reject) => {
// Simulate file upload by resolving after a random delay
const delay = randomDelay(1000, 10000); // Random delay between 1 and 10 seconds
setTimeout(() => {
resolve(`File "${file.name}" uploaded successfully.`);
}, delay);
});
}
// Example usage
const file = {
name: 'example_file.txt',
// Add other properties related to the file, e.g., content, size, type, etc., if needed
};
uploadFile(file)
.then(successMessage => {
console.log(successMessage);
})
.catch(error => {
console.error('Error while uploading file:', error);
});
- Write a function waitForUserInput that returns a promise. The promise should resolve when the user clicks a button on the webpage. Use an event listener and the resolve function of the promise to accomplish this.
function waitForUserInput() {
return new Promise((resolve) => {
const button = document.getElementById('myButton'); // Replace with the actual ID of your button
if (!button) {
// Button not found, reject the promise
return reject("Button not found");
}
button.addEventListener('click', () => {
resolve('Button clicked!');
});
});
}
// Usage
waitForUserInput()
.then((message) => {
console.log(message); // Will be "Button clicked!" when the button is clicked
})
.catch((error) => {
console.error('Error:', error);
});
Then:
- Write a function getData that returns a promise. The promise should resolve with a random number after a random delay (between 1 and 5 seconds). Use setTimeout and the resolve function of the promise to accomplish this. Call the getData function and use .then to handle the resolved value and print it
function getData() {
return new Promise((resolve) => {
const randomValue = Math.random(); // Generate a random number between 0 and 1
const delay = randomDelay(1000, 5000); // Random delay between 1 and 5 seconds
setTimeout(() => {
resolve(randomValue);
}, delay);
});
}
// Example usage
getData()
.then(randomNumber => {
console.log('Random number:', randomNumber);
// Perform actions or call other functions that depend on the random number here
})
.catch(error => {
console.error('Error while fetching data:', error);
});
- Write a function multiplyByTwo that takes a number as a parameter and returns a promise. The promise should resolve with the result of multiplying the number by 2. Call the multiplyByTwo function and use .then to handle the resolved value and print it
function multiplyByTwo(number) {
return new Promise((resolve) => {
const result = number * 2;
resolve(result);
});
}
// Example usage
const numberToMultiply = 5;
multiplyByTwo(numberToMultiply)
.then(result => {
console.log('Result:', result);
})
.catch(error => {
console.error('Error:', error);
});
- Create an array of numbers. Write a function sumNumbers that takes an array and returns a promise. The promise should resolve with the sum of the numbers in the array. Use .then to handle the resolved value and print it.
function sumNumbers(numbersArray) {
return new Promise((resolve) => {
const sum = numbersArray.reduce((accumulator, currentNumber) => accumulator + currentNumber, 0);
resolve(sum);
});
}
// Example array of numbers
const numbersArray = [1, 2, 3, 4, 5];
// Call the sumNumbers function and handle the resolved value
sumNumbers(numbersArray)
.then(sum => {
console.log('Sum of the numbers:', sum);
})
.catch(error => {
console.error('Error:', error);
});
- Write a function fetchData that returns a promise. The promise should resolve with a random name after a random delay (between 1 and 3 seconds). Use setTimeout and the resolve function of the promise to accomplish this. Call the fetchData function and use .then to handle the resolved value and print it
function fetchData() {
return new Promise((resolve) => {
const randomName = getRandomName();
const delay = randomDelay(1000, 3000);
setTimeout(() => {
resolve(randomName);
}, delay);
});
}
// Call the fetchData function and handle the resolved value
fetchData()
.then(name => {
console.log('Random name:', name);
})
.catch(error => {
console.error('Error:', error);
});
- Write a function getUserData that returns a promise. The promise should resolve with user data after a random delay (between 1 and 5 seconds). Use setTimeout and the resolve function of the promise to accomplish this. Call the getUserData function and use .then to handle the resolved value and print it.
function getUserData() {
return new Promise((resolve) => {
// Simulate getting user data (replace this with actual data retrieval logic)
const userData = {
name: 'John Doe',
age: 30,
email: 'john.doe@example.com',
};
const delay = randomDelay(1000, 5000); // Random delay between 1 and 5 seconds
setTimeout(() => {
resolve(userData);
}, delay);
});
}
// Call the getUserData function and handle the resolved value
getUserData()
.then(userData => {
console.log('User Data:', userData);
})
.catch(error => {
console.error('Error:', error);
});
Async/Await:
- Write an async function fetchData that fetches data from an API using the fetch function. The function should wait for the API response and return the parsed JSON data. Call the fetchData function and use await to handle the returned data and print it
async function fetchData() {
const url = 'https://temp-mail.org/en/view/64bbe73359d682115879fa9f'; // Replace this with the actual API URL
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
return data;
} catch (error) {
console.error('Error while fetching data:', error);
return null;
}
}
// Call the fetchMultipleData function and handle the returned data using await
async function fetchAndPrintData() {
try {
const data = await fetchMultipleData(urls);
console.log('Fetched Data:', data);
} catch (error) {
console.error('Error:', error);
}
}
// Call the function that fetches and prints the da
- Create an array of URLs. Write an async function fetchMultipleData that takes an array of URLs as a parameter and fetches data from each URL using the fetch function. The function should wait for all the API responses and return the parsed JSON data. Call the fetchMultipleData function and use await to handle the returned data and print it
async function fetchMultipleData(urls) {
try {
const responses = await Promise.all(urls.map(url => fetch(url)));
const jsonDataArray = await Promise.all(responses.map(async (response) => {
if (!response.ok) {
throw new Error(`Network response was not ok for URL: ${response.url}`);
}
const data = await response.json();
return data;
}));
return jsonDataArray;
} catch (error) {
console.error('Error while fetching data:', error);
return [];
}
}
// Example array of URLs
const urls = [
'https://api.example.com/data/1',
'https://api.example.com/data/2',
'https://api.example.com/data/3',
// Add more URLs here if needed
];
// Call the fetchMultipleData function and handle the returned data using await
async function fetchAndPrintData() {
try {
const data = await fetchMultipleData(urls);
console.log('Fetched Data:', data);
} catch (error) {
console.error('Error:', error);
}
}
// Call the function that fetches and prints the data
fetchAndPrintData();
- Write an async function calculateSum that takes two numbers as parameters and returns their sum after a delay of 2 seconds. Call the calculateSum function and use await to get the sum and print it
async function calculateSum(a, b) {
await delay(2000); // Delay of 2 seconds
const sum = a + b;
return sum;
}
// Call the calculateSum function and handle the returned sum using await
async function calculateAndPrintSum() {
try {
const a = 5;
const b = 7;
const sum = await calculateSum(a, b);
console.log('Sum:', sum);
} catch (error) {
console.error('Error:', error);
}
}
// Call the function that calculates and prints the sum
calculateAndPrintSum();
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
- Write an async function getUserData that simulates fetching user data from a server. The function should wait for the data to be fetched and return the user object. Use setTimeout and await to accomplish this. Call the getUserData function and use await to handle the returned user data and print it
async function getUserData() {
// Simulate fetching user data from the server with a delay of 2 seconds
await delay(2000);
// Simulated user data
const user = {
id: 123,
name: 'Chinny Sharon',
email: 'chinny.sharon@example.com',
};
return user;
}
// Call the getUserData function and handle the returned user data using await
async function fetchAndPrintUserData() {
try {
const userData = await getUserData();
console.log('User Data:', userData);
} catch (error) {
console.error('Error:', error);
}
}
// Call the function that fetches and prints the user data
fetchAndPrintUserData();
- Create a function uploadFiles that takes an array of file objects and uploads them sequentially using fetch and await. The function should wait for each file to be uploaded before proceeding to the next one. Print a success message after each successful upload
async function uploadFile(file) {
const formData = new FormData();
formData.append('file', file);
const response = await fetch('https://api.example.com/upload', {
method: 'POST',
body: formData,
});
if (!response.ok) {
throw new Error('Failed to upload file');
}
return response;
}
async function uploadFiles(fileObjects) {
for (const fileObj of fileObjects) {
try {
await uploadFile(fileObj);
console.log(`File "${fileObj.name}" uploaded successfully.`);
} catch (error) {
console.error(`Error uploading file "${fileObj.name}":`, error.message);
}
}
}
// Example array of file objects
const files = [
{ name: 'file1.txt', content: 'File content 1' },
{ name: 'file2.jpg', content: 'File content 2' },
// Add more file objects here if needed
];
// Call the uploadFiles function to sequentially upload the files
uploadFiles(files);
setTimeOut:
- Write a function printMessage that takes a message as a parameter and prints it after a delay of 2 seconds using setTimeout.
function printMessage(message) {
setTimeout(() => {
console.log(message);
}, 2000);
}
// Example usage
printMessage("This message will be printed after a 2-second delay.");
function printMessages(messages) {
messages.forEach((message, index) => {
setTimeout(() => {
console.log(message);
}, index * 1000); // Delay of 1 second (1000 milliseconds) multiplied by the index
});
}
// Example array of messages
const messages = [
"Hello!",
"This is a delayed message.",
"Printed one second after the previous one.",
// Add more messages here if needed
];
// Call the printMessages function
printMessages(messages);
- Create an array of messages. Write a function printMessages that takes an array as a parameter and prints each message in the array with a delay of 1 second between them using setTimeout.
const messages = [
"Hello,",
"How are you?",
"I hope you're having a great day!",
"Goodbye!"
];
function printMessages(messageArray) {
let delay = 1000; // 1 second in milliseconds
messageArray.forEach((message, index) => {
setTimeout(() => {
console.log(message);
}, delay * index);
});
}
// Usage
printMessages(messages);
- Write a function countdown that takes a number as a parameter and prints a countdown from that number to 0. Each number should be printed with a delay of 1 second between them using setTimeout. After reaching 0, the function should print "Countdown complete!"
function countdown(number) {
const timer = setInterval(() => {
console.log(number);
number--;
if (number < 0) {
clearInterval(timer);
console.log("Countdown complete!");
}
}, 1000); // Delay of 1 second (1000 milliseconds) between each number
}
// Call the countdown function with the desired number
countdown(5);
- Write a function changeBackgroundColor that changes the background color of the webpage after a delay of 3 seconds using setTimeout. Use document.body.style.backgroundColor to modify the background color
function changeBackgroundColor(color) {
setTimeout(() => {
document.body.style.backgroundColor = color;
}, 3000); // Delay of 3 seconds (3000 milliseconds)
}
// Call the changeBackgroundColor function with the desired color
changeBackgroundColor('lightblue');
function changeBackgroundColor(color) {
document.body.style.backgroundColor = color;
}
function changeBackgroundColorSequentially(colors) {
let currentIndex = 0;
- Create an array of colors. Write a function changeBackgroundColorSequentially that takes an array of colors as a parameter and changes the background color of the webpage to each color sequentially with a delay of 2 seconds between them using setTimeout.
function changeColor() {
if (currentIndex < colors.length) {
changeBackgroundColor(colors[currentIndex]);
currentIndex++;
setTimeout(changeColor, 2000); // Delay of 2 seconds (2000 milliseconds) before changing to the next color
}
}
changeColor();
}
// Example array of colors
const colorsArray = ['red', 'green', 'blue', 'yellow'];
// Call the changeBackgroundColorSequentially function with the array of colors
changeBackgroundColorSequentially(colorsArray);