I need some help with a problem I'm working on. Here are the instructions:
Write a function called carFactory that takes in three parameters: a make, model, and year.
When the function is invoked:
Inside the function, create an object from those parameters. Next, write an if statement that will check if the year sent in is greater than 2018.
Last, the function should return the object. For example:
carFactory('toyota', 'camry', 2020)
// should return an object that looks like this:
{
make: 'toyota',
model: 'camry',
year: 2020,
isNew: true
};
This is what I have so far, but it's not producing the desired results. Any help would be greatly appreciated.
function carFactory(make, model, year) {
this.make = 'make';
this.model = 'model';
this.year = 'year';
let newCar = {
make: this.make,
model: this.model,
year: this.year,
}
if (year > 2018) {
carFactory.isNew = true;
} else {
carFactory.isNew = false;
}
};
let newCar = new carFactory('toyota', 'camry', 2020);
console.log(newCar);
You can create a Car class and return the new car instance from the factory. This will give you the expected output
class Car {
constructor(make, model, year) {
Object.assign(this, { make, model, year });
}
}
const carFactory = (make, model, year) => {
const newCar = new Car(make, model, year);
newCar.isNew = (year > 2018);
return newCar;
};
const newCar = carFactory('toyota', 'camry', 2020);
console.log({ newCar });
Try like this:
function carFactory(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
year > 2018 ? this.isNew = true : this.isNew = false
};
let newCar = new carFactory('toyota', 'camry', 2020);
console.log(newCar);