In: Computer Science
Create a class named Ship with a field that stores a collection of Shippable things and another that stores a maximum weight capacity. Include a constructor with a parameter for the max weight, and that gives the Ship an empty collection of Shippables. (Javascript)
Hello,
I have created Ship class based on your requirement. I have created colloection of Shippable things in class with both Set and arrays. You can use either of them as per your convenience. And also I haave provided code snippet to test Ship class. Please let me know if you need any changes required. Below is the code shippets.
Ship class with Collection Set used for holding shippables:
// Createing Ship class with constructor has one parameter that is maxWeightCapacity
class Ship {
constructor(maxWeightCapacity) {
// Set maxWeightCapacity value based on constructor parameter value
this.maxWeightCapacity = maxWeightCapacity;
// Assign empty set to shippables field value
this.shippables = new Set();
}
}
// Test Ship class
// Created ship1 object with maxWeightCapacity 1000 by using constructor
const ship1 = new Ship(1000);
// Print maxWeightCapacity value within ship1 object
console.log(ship1.maxWeightCapacity);
// Add new item to shippables Set
ship1.shippables.add({
weight: 10
});
// Add new item to shippables Set
ship1.shippables.add({
weight: 20
});
// Print shippables value within ship1 object
console.log(ship1.shippables);
Ship class with Arrays used for holding shippables:
// Createing Ship class with constructor has one parameter that is maxWeightCapacity
class Ship {
constructor(maxWeightCapacity) {
// Set maxWeightCapacity value based on constructor parameter value
this.maxWeightCapacity = maxWeightCapacity;
// Assign empty array to shippables field value
this.shippables = [];
}
}
// Test Ship class
// Created ship2 object with maxWeightCapacity 500 by using constructor
const ship2 = new Ship(500);
// Print maxWeightCapacity value within ship1 object
console.log(ship2.maxWeightCapacity);
// Add new object to shippables array
ship2.shippables.push({
weight: 15
});
// Add new object to shippables array
ship2.shippables.push({
weight: 35
});
// Print shippables value within ship2 object
console.log(ship2.shippables);