0

So I am currently working through some code academy problems and was thinking about the "recommended" solution from them. The code is as follows:

  ...

  getRandomDishFromCourse(courseName) {
    ...
    return this._courses['appetizers'];
  },

  generateRandomMeal() {
    const appetizer = this.getRandomDishFromCourse('appetizers');
    ...

    return `Your meal is ${appetizer.name}...`
  }

So they call the getRandomDishFromCourse with a string as an argument and then in the function I access the object through the bracket notation. How would I solve this with getters and setters instead? What is the best practice for this?

My idea for solving this is presented below, but does not work...

  get appetizers() {
    return this._courses._appetizers;
  },

  ...

  getRandomDishFromCourse(courseName) {
    let dish = courseName;
    return dish;
    ...
  },

  generateRandomMeal() {
    const appetizer = this.getRandomDishFromCourse(this.appetizers);
    ...

    return `Your meal is ${appetizer.name}...`
  }
3
  • 1
    Please create a working snippet demonstrating your problem. Commented Mar 21, 2018 at 12:41
  • Note that your set for appetizers accessors is incorrect: It doesn't set appetizers, it adds to appetizers. Just adding to the array isn't a use-case for a setter. Commented Mar 21, 2018 at 12:44
  • @T.J.Crowder thanks for the input, I have actually removed the setter since the question is valid only for the getter. My basic question is how do you "pass" a getter instead of passing a string that you access through bracket notation? Commented Mar 21, 2018 at 12:48

1 Answer 1

2

My basic question is how do you "pass" a getter instead of passing a string that you access through bracket notation?

You don't. But you can pass the array:

getRandomDishFromCourse(course) {
  let disk = course[Math.floor(course.length * Math.random())];
  return dish;
},

generateRandomMeal() {
  const appetizer = this.getRandomDishFromCourse(this.appetizers);
  // ...
}

...or a function that gets the appropriate array:

getRandomDishFromCourse(getCourse) {
  let course = getCourse();
  let disk = course[Math.floor(course.length * Math.random())];
  return dish;
},

generateRandomMeal() {
  const appetizer = this.getRandomDishFromCourse(() => this.appetizers);
  // ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Great! Thanks that makes sense!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.