Files

53 lines
1.6 KiB
TypeScript

import type { Id } from "../convex/_generated/dataModel"
import { COVER_GRID_ALBUMS } from "../convex/limits"
import type { BrowseSong } from "../convex/types"
export { COVER_GRID_ALBUMS }
export type CoverAlbum = BrowseSong["album"]
/** Distinct albums that have artwork, in playlist order. */
export function playlistCoverAlbums(songs: readonly BrowseSong[]) {
const albums = new Map<string, CoverAlbum>()
for (const song of songs) {
if (song.album.cover !== null && !albums.has(song.album.id)) {
albums.set(song.album.id, song.album)
}
}
return [...albums.values()]
}
/** `count` distinct items in random order (Fisher-Yates prefix). */
function sample<T>(items: readonly T[], count: number) {
const pool = [...items]
for (let index = 0; index < count; index++) {
const swap = index + Math.floor(Math.random() * (pool.length - index))
;[pool[index], pool[swap]] = [pool[swap], pool[index]]
}
return pool.slice(0, count)
}
/**
* Cover options to pick from, as album ids for `setPlaylistCoverAlbums`.
* With four or more albums: `count` random 2x2 grids, avoiding repeats.
* With fewer: each album's cover alone.
*/
export function randomPlaylistCovers(
albums: readonly CoverAlbum[],
count = 4
): Id<"albums">[][] {
const ids = albums.map((album) => album.id)
if (ids.length < COVER_GRID_ALBUMS) return ids.map((id) => [id])
const options = new Map<string, Id<"albums">[]>()
for (
let attempt = 0;
options.size < count && attempt < count * 10;
attempt++
) {
const option = sample(ids, COVER_GRID_ALBUMS)
options.set(option.join(","), option)
}
return [...options.values()]
}