Home > Net >  Writing a function that returns an object (carFactory)
Writing a function that returns an object (carFactory)

Time:09-17

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:

  • a string will be sent in for make
  • a string will be sent in for model
  • a number will be sent in for year

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.

  • If the year is greater than 2018, add a key to the object called isNew and set it to true
  • else, add a key to the object called isNew and set it to false

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);

CodePudding user response:

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 });

CodePudding user response:

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);

  • Related