52 lines
1.3 KiB
JavaScript
52 lines
1.3 KiB
JavaScript
function calculateTotalPrice(items = []) {
|
|
// let total = 0;
|
|
// items.forEach((item) => {
|
|
// total += item.price;
|
|
// });
|
|
const total = items.reduce((sum, item) => {
|
|
// Ensure that item.price is a number
|
|
const price = typeof item.price === 'number' ? item.price : Number(item.price);
|
|
|
|
if (isNaN(price)) {
|
|
console.warn(`Invalid price for item "${item.name}". Skipping...`);
|
|
return sum;
|
|
}
|
|
return sum + Number(item.price);
|
|
}, 0);
|
|
|
|
return Number(total.toFixed(2));
|
|
}
|
|
|
|
const shoppingCart = [
|
|
{ name: 'Laptop', price: 999.99 },
|
|
{ name: 'Smartphone', price: 599.99 },
|
|
{ name: 'Headphones', cost: 199.99 },
|
|
];
|
|
|
|
const totalPrice = calculateTotalPrice(shoppingCart);
|
|
console.log('Total Price:', totalPrice);
|
|
|
|
function displayUserProfile(user) {
|
|
console.log(`Name: ${user.name}`);
|
|
console.log(`Age: ${user.age}`);
|
|
console.log(`Email: ${user.email.toLowerCase()}`);
|
|
}
|
|
|
|
const userProfile = {
|
|
name: 'Sarah',
|
|
age: 'twenty-five',
|
|
email: 'SARAH@EXAMPLE.COM',
|
|
};
|
|
|
|
displayUserProfile(userProfile);
|
|
|
|
function getFirstItemName(items) {
|
|
return items[0].name.toUpperCase();
|
|
}
|
|
|
|
console.log('First Item:', getFirstItemName(shoppingCart)); // => LAPTOP
|
|
|
|
const numberList = [1, 2, 3, 4, 5];
|
|
const sum = numberList.reduce((acc, num) => acc + Number(num), 0);
|
|
console.log('Sum:', sum); // => 15
|