Build a library


#1

Hello fellow coders!
I managed to finish this exercise, incredibly without errors. But many mistakes were made because my results make no sense :disappointed_relieved:
In particular the “rating” area is problematic.
Sorry in advance for this shame of code, please give me a hint!

class Media {
  constructor (title) {
    this._title = title;
    this._isCheckedOut = false;
    this._ratings = [''];
  }
  
  get title() {
    return this._title;
  }
  get isCheckedOut() {
    return this._isCheckedOut;
  }
  get ratings() {
    return this._ratings;
  }
  
  set isCheckedOut(checked) {
    this._isCheckedOut = checked;
  }
  
  toggleCheckOutStatus() {
    this._isCheckedOut = !this._isCheckedOut;
  }
  getAverageRating() {
    let ratingSum = this.ratings.reduce((currentSum, rating) => currentSum + rating, 0);
    const lengthOfArray = this.ratings.length;
    return ratingSum / lengthOfArray;
  }
  addRating(newRating) {
    this.ratings.push(newRating);
  }
};

class Book extends Media {
  constructor (author, title, pages) {
    super(title);
    this._author = author;
    this._pages = pages;
  }
  
  get author() {
    return this._author;
  }
  get pages() {
    return this._pages;
  }
};

class Movie extends Media {
  constructor (director, title, runTime) {
    super (title);
    this._director = director;
    this._runTime = runTime;
  }
};

const historyOfEverything = new Book('Bill Bryson', 'A Short History of Nearly Everything', 544)
historyOfEverything.toggleCheckOutStatus();
console.log(historyOfEverything.isCheckedOut); // output> true
historyOfEverything.addRating(4);
historyOfEverything.addRating(5);
historyOfEverything.addRating(5);
console.log(historyOfEverything.getAverageRating())  // output> 113!?
console.log(Media.ratings) // output> undefined

const speed = new Movie('Jan de Bont', 'Speed', 116);
speed.toggleCheckOutStatus();
console.log(speed.isCheckedOut); // output> true
speed.addRating(1);
speed.addRating(1);
speed.addRating(5);
console.log(speed.getAverageRating()) // output> 28.75...

#2

look:

  getAverageRating() {
    let ratingSum = this.ratings.reduce((currentSum, rating) => currentSum + rating, 0);
    console.log(ratingSum)
    const lengthOfArray = this.ratings.length;
    return ratingSum / lengthOfArray;
  }

as you can see ratingSum is a string, string (ratingSum) divided by integer (lengthOfArray) gives weird behavior


#3

I was running mad because of that
this._ratings = [''];
and it was just a little thing… this reminded me that coding is very challenging!
Thank you stetim


#4

so all good now?


#5

Yes thank you again!