Build a library


#1

I am having issues on getting the average Rating , it returns undefined. Anyone can explain why?

class Media {
constructor(title) {
this._title= title;
this._isCheckedOut= false;
this._rating = [];
}

get title() {
return this._title;
}

get isCheckedOut() {
return this._isCheckedOut;
};

get rating() {
return this._rating;
}

set isCheckedOut(isCheckedOut) {
this._isCheckedOut = isCheckedOut;
}

toggleCheckOutStatus() {
this._isCheckedOut=!this._isCheckedOut;
// if (this._isCheckedOut = true) {
// this._isCheckedOut = false;
// }
// else{
// this._isCheckedOut = true;/
};

getAverageRating () {

let ratingSum = this._rating.reduce((currentSum, rating) => currentSum + rating, 0);

let lengthOfArray = this._rating.length;

let averageRating = Math.round(ratingSum / lengthOfArray) ;
//console.log(averageRating) ;
this._ratings = averageRating;
};

addRating (rating) {
this._rating.push(rating);
}
}

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=0;
}
get director () {
return this._director;
}
get runtime() {
return this._runtime;
}
}

const historyOfEverything = new Book (‘Bill Bryson’,‘A Short History of Nearly Everything’,544);
historyOfEverything.toggleCheckStatus;
historyOfEverything.isCheckedOut=true;
historyOfEverything.toggleCheckStatus;
historyOfEverything.addRating(4);
historyOfEverything.addRating(5);
historyOfEverything.addRating(5);

console.log(historyOfEverything.getAverageRating());
console.log(historyOfEverything);


Build a Library
#2

getAverageRating doesn’t return anything, so the default value (undefined) is returned.

also, in your getAverageRating method, this line:

this._ratings = averageRating;

is a bad idea. Now ratings is a integer, so then if we call the getAverageRating method again, we will get an error given an integer doesn’t have .length property


#3

Modified getAverageRating to return averageRating and it still did work properly . However I noticed that I have to add () when console.log(historyOfEverything.getAverageRating()) and then it worked ok.

Why is that ?


#4

modified how? Please post an updated version of your code, otherwise i have to guess what and how you changed things :wink:

looking at your original code you posted in this topic:

console.log(historyOfEverything.getAverageRating());

you already had ()? I am slightly confused by this question


#5

Sorry, It is not shown here but I had a second instance for Movie which did not have () and it didn’t return anything but only after I added the ().