35 lines
985 B
TypeScript
35 lines
985 B
TypeScript
import { matchWords, searchWords } from "./fuzzy-search"
|
|
|
|
type SearchableSong = {
|
|
id: string
|
|
title: string
|
|
artist: { name: string }
|
|
album: { title: string }
|
|
}
|
|
|
|
/**
|
|
* Case-insensitive match on title, artist, or album, give or take typos (see
|
|
* `matchWords`), plus the songs in `lyricsMatches` (from
|
|
* `api.lyrics.matchingSongIds`). A blank query keeps every song.
|
|
*/
|
|
export function filterSongs<T extends SearchableSong>(
|
|
songs: T[],
|
|
query: string,
|
|
lyricsMatches?: readonly string[]
|
|
) {
|
|
const normalized = query.trim().toLowerCase()
|
|
if (!normalized) {
|
|
return songs
|
|
}
|
|
const terms = searchWords(normalized)
|
|
const byLyrics = new Set(lyricsMatches)
|
|
return songs.filter((song) => {
|
|
if (byLyrics.has(song.id)) return true
|
|
const fields = [song.title, song.artist.name, song.album.title]
|
|
return (
|
|
fields.some((value) => value.toLowerCase().includes(normalized)) ||
|
|
matchWords(searchWords(fields.join(" ")), terms) !== null
|
|
)
|
|
})
|
|
}
|