Hi all!
I wanted to show you how I solved the additional task on the Build a Library project!
I’m only going to copy and paste the class Media
and class CD extends Media
.
class Media {
constructor(title) {
this._title = title;
this._isCheckOut = false;
this._ratings = [];
}
get title() {
return this._title;
}
get isCheckedOut() {
return this._isCheckedOut;
}
get ratings() {
return this._ratings;
}
set isCheckedOut(v) {
this._isCheckedOut = v;
}
toggleCheckOutStatus() {
this.isCheckedOut = !this.isCheckedOut;
}
getAverageRating() {
let sum = this.ratings.reduce((a, b) => a + b);
return sum / this.ratings.length;
}
addRating(n) {
if (n >= 1 && n <= 5) {
this.ratings.push(n);
} else {
console.log(`Rating should be between 1 to 5.`);
}
}
}
class CD extends Media {
constructor(singer, title, runTime, songTitles) {
super(title);
this._singer = singer;
this._runTime = runTime;
this._songTitles = [];
}
get singer() {
return this._singer;
}
get runTime() {
return this._runTime;
}
get songTitles() {
return this._songTitles;
}
addSongTitles(arr) {
for (let i = 0; i < arr.length; i++) {
this.songTitles.push(arr[i]);
}
}
shuffle() {
function compare() {
return Math.random() - .5;
}
const shuffledArr = this.songTitles;
shuffledArr.sort(compare);
return shuffledArr;
}
}
//creating a new variable
const proofAlbum = new CD('BTS', 'Proof', 15);
//adding song titles to the album
proofAlbum.addSongTitles(['Born Singer', 'Boy In Luv', 'I Need U','Life Goes On', 'Butter']);
//logging the array of song titles
console.log(proofAlbum.songTitles);
//logging the shuffled array of song titles
console.log(proofAlbum.shuffle());
Note (what I’ve learned through this task):
- The
sort()
method is used to sort the elements of an array in place and returns the sorted array. By providing a custom comparison function as an argument to thesort()
method, you can sort an array in any desired order or based on any criteria. - The expression
Math.random() - 0.5
generates a random number that is centered around 0. The resulting number can be positive, negative, or zero. When this comparison function is used in thesort()
method, it compares pairs of elements in the array being sorted. If the result ofcompare(a, b)
is less than 0, thena
comes beforeb
in the sorted array. If the result is greater than 0, thenb
comes beforea
. If the result is 0, then the order ofa
andb
is left unchanged. By usingMath.random() - 0.5
as the comparison function, we are effectively randomizing the order of the elements in the array being sorted. Since the result of the comparison function is random for each pair of elements, the resulting order of the array is also random.
Happy coding!