Build a Library project (shuffle method solved)

Hi all! :slight_smile:
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):

  1. 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 the sort() method, you can sort an array in any desired order or based on any criteria.
  2. 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 the sort() method, it compares pairs of elements in the array being sorted. If the result of compare(a, b) is less than 0, then a comes before b in the sorted array. If the result is greater than 0, then b comes before a. If the result is 0, then the order of a and b is left unchanged. By using Math.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! :blue_heart:

Great work with helper function and higher order function. When it comes down to it we can simplify to a simple return statement

return this.songTitles.sort(compare)

On top of that simplification, we can leverage the concise body function on the helper:

const compare = () => Math.random() - 0.5;

which gets your method down to two very readable lines.

Furthermore, given that the helper couldn’t be simpler, and it is contained in the function, do we even need it?

    shuffle () {
        return this.songTitles.sort(() => Math.random() - 0.5)
    }

Any reader will put this together in a single heartbeat. It’s a rare occasion that we get to refactor to this level of simplicity. One may venture to say, take advantage of the opportunity when it presents itself, and, we won’t face criticism for doing it this way. Simple isn’t always best, but this one time I think we can go with it.

1 Like

Hi! :smiley:
Thank you for your time on sharing such a great tip on simplifying the code. It looks great! :+1: :pray:

1 Like

To let you in on where my thinking comes from: Physics.

Variables, to my mind represent concepts.

F = kma

Some vector ‘F’ is dependent upon some 'k’onstant of variabtion times some mass times some acceleration vector.

Concept equals concept times concept times concept.

It’s a big ask, but how would you equate this understanding to the above refactoring?