refactor: simplify function signatures for counting songs and retrieving top N songs

This commit is contained in:
Rémi Heredero 2025-04-07 13:04:49 +02:00
parent 0c34a2df52
commit 3d52397ef8
Signed by: Klagarge
GPG Key ID: 735B36B074A65F0F

View File

@ -106,7 +106,7 @@ case class TopSongs(songs: List[Song] = List()) {
// It uses flatMap to extract the artist names from the songs
// Then it groups the songs by artist name and counts the occurrences
// Finally, it returns a map with the artist names as keys and the counts as values
def countSongsByArtist(songs: List[Song]): Map[String, Int] = {
def countSongsByArtist(): Map[String, Int] = {
songs.flatMap(_.singer.map(_.person.name))
.groupBy(identity)
.view.mapValues(_.size)
@ -115,7 +115,7 @@ case class TopSongs(songs: List[Song] = List()) {
// This function returns the top N songs by weeks on chart
// It sorts the songs by the streak value in descending order and takes the top N songs
def topNSongsByWeeks(songs: List[Song], n: Int): List[Song] = {
def topNSongsByWeeks(n: Int): List[Song] = {
songs.sortBy(song => -song.rank._1.streak.getOrElse(0)).take(n)
}
@ -156,19 +156,20 @@ case class TopSongs(songs: List[Song] = List()) {
// print the songs
topSongs.printSongs()
println("----------");
println("----------")
// print the number of songs by artist
val songsByArtist = topSongs.countSongsByArtist(topSongs.songs)
val songsByArtist = topSongs.countSongsByArtist()
println("Number of songs by artist:")
songsByArtist.foreach {
case (artist, count) => println(s"$artist: $count")
}
println("----------");
println("----------")
// print the top N songs by weeks on chart
val topNSongs = topSongs.topNSongsByWeeks(topSongs.songs, 5)
val topNSongs = topSongs.topNSongsByWeeks(5)
println("Top N songs by weeks on chart:")
topNSongs.foreach { song =>
println(s"${song.title} by ${song.singer.map(_.person.name).mkString(", ")} - ${song.rank._1.streak.getOrElse(0)} weeks")