This repository contains solutions for 3 tasks focused on objects, arrays, and methods in JavaScript. Each task is implemented in a separate file (task-1.js, task-2.js, task-3.js).
A function that checks if all products can fit into a container with limited size.
function isEnoughCapacity(products, containerSize) {
const total = Object.values(products).reduce((sum, qty) => sum + qty, 0);
return total <= containerSize;
}
✅ Test Results
isEnoughCapacity({ apples: 2, grapes: 3, carrots: 1 }, 8);
// true
isEnoughCapacity({ apples: 4, grapes: 6, lime: 16 }, 12);
// false
isEnoughCapacity({ apples: 1, lime: 5, tomatos: 3 }, 14);
// true
isEnoughCapacity({ apples: 18, potatos: 5, oranges: 2 }, 7);
// false
A function that calculates the average daily calories consumed over a week. If no data is provided, it returns 0.
function calcAverageCalories(days) {
if (days.length === 0) return 0;
const total = days.reduce((sum, item) => sum + item.calories, 0);
return total / days.length;
}
✅ Test Results
calcAverageCalories([
{ day: "monday", calories: 3010 },
{ day: "tuesday", calories: 3200 },
{ day: "wednesday", calories: 3120 },
{ day: "thursday", calories: 2900 },
{ day: "friday", calories: 3450 },
{ day: "saturday", calories: 3280 },
{ day: "sunday", calories: 3300 }
]);
// 3180
calcAverageCalories([
{ day: "monday", calories: 2040 },
{ day: "tuesday", calories: 2270 },
{ day: "wednesday", calories: 2420 },
{ day: "thursday", calories: 1900 },
{ day: "friday", calories: 2370 },
{ day: "saturday", calories: 2280 },
{ day: "sunday", calories: 2610 }
]);
// 2270
calcAverageCalories([]);
// 0
An object representing a player profile with username, play time, and methods to update data and return formatted information.
const profile = {
username: "Jacob",
playTime: 300,
changeUsername(newName) {
this.username = newName;
},
updatePlayTime(hours) {
this.playTime += hours;
},
getInfo() {
return `${this.username} has ${this.playTime} active hours!`;
},
};
✅ Test Results
profile.getInfo();
// "Jacob has 300 active hours!"
profile.changeUsername("Marco");
profile.getInfo();
// "Marco has 300 active hours!"
profile.updatePlayTime(20);
profile.getInfo();
// "Marco has 320 active hours!"
With this homework, you practiced:
- Creating and updating objects
- Iterating over object properties
- Working with arrays of objects
- Adding and using methods inside objects
- Using
spreadandrestoperators - Applying
thisto access object properties
These exercises strengthen your foundation in JavaScript and help you write cleaner, reusable code 🚀
- Task 1: Product Packaging with object values and reduce
- Task 2: Average calories from an array of objects
- Task 3: Player profile with methods and
this