Instantly share code, notes, and snippets.

Embed
What would you like to do?
const secrets = {
LASTFM_KEY: '',
LASTFM_USER: '',
}
let albums = []
fetch(
`https://ws.audioscrobbler.com/2.0/?method=user.gettopalbums&user=${
secrets.LASTFM_USER
}&api_key=${secrets.LASTFM_KEY}&format=json`
)
.then(res => res.json())
.then(json => {
if (json.topalbums) {
json.topalbums.album.forEach(album => {
const record = {
name: album.name,
artist: album.artist.name,
totalPlaycount: parseInt(album.playcount, 10),
}
fetch(
`https://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=${
secrets.LASTFM_KEY
}&autocorrect=1&artist=${record.artist}&album=${record.name}&format=json`
)
.then(res => res.json())
.then(json => {
if (json.album) {
// some (~20%!) albums don't have tracklistings,
// making the following calculations throw errors
// if we don't check that the tracklisting exists first
if (json.album.tracks.track.length !== 0) {
record.totalTracks = json.album.tracks.track.length
// we're calculating a playthrough here as scrobbles / # of tracks.
// a better solution would be to calculate the duration of each track
// as a percentage of the record, and add each scrobble individually.
// i did not do that, because i am lazy and this isn't real.
record.playthroughs = record.totalPlaycount / record.totalTracks
record.duration = json.album.tracks.track
.map(track => parseInt(track.duration, 10))
.reduce((a, b) => a + b)
// this is the part with our ranking algorithm
record.rank = record.playthroughs * (1 + record.duration / 2700)
albums.push(record)
}
}
})
})
}
})
albums = albums.sort((a, b) => a.rank > b.rank ? -1 : 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment