From de176acd8f13b5a18e2dd8bb9a09085b05cb128f Mon Sep 17 00:00:00 2001 From: Izan Gil <66965250+SrIzan10@users.noreply.github.com> Date: Sat, 31 May 2025 17:58:52 +0200 Subject: [PATCH] chore: use fisheryates for array shuffle --- src/lib/fisheryates.ts | 13 +++++++++++++ src/lib/state.svelte.ts | 2 +- src/lib/stations/sleep.ts | 4 +++- src/lib/types.ts | 4 ++-- 4 files changed, 19 insertions(+), 4 deletions(-) create mode 100644 src/lib/fisheryates.ts diff --git a/src/lib/fisheryates.ts b/src/lib/fisheryates.ts new file mode 100644 index 0000000..f2804b6 --- /dev/null +++ b/src/lib/fisheryates.ts @@ -0,0 +1,13 @@ +// source: https://decipher.dev/30-seconds-of-typescript/docs/shuffle/ +// modified to use existing SIMDMersenneTwister constructor for random number generation + +import type { SIMDMersenneTwister } from "./mersenne"; + +export const fisherYates = (sfml: SIMDMersenneTwister, ...arr: any[]) => { + let m = arr.length; + while (m) { + const i = Math.floor(sfml.random() * m--); + [arr[m], arr[i]] = [arr[i], arr[m]]; + } + return arr; +}; \ No newline at end of file diff --git a/src/lib/state.svelte.ts b/src/lib/state.svelte.ts index 1676588..b239225 100644 --- a/src/lib/state.svelte.ts +++ b/src/lib/state.svelte.ts @@ -14,7 +14,7 @@ export const state = $state({ isLoading: true, error: null as string | null, currentTime: 0, - duration: 0 as number | undefined, + duration: 0, presets: [] as Preset[], stations: [] as Station[], diff --git a/src/lib/stations/sleep.ts b/src/lib/stations/sleep.ts index c5448f6..a570446 100644 --- a/src/lib/stations/sleep.ts +++ b/src/lib/stations/sleep.ts @@ -1,5 +1,6 @@ import type { Song } from "@/types"; import { SIMDMersenneTwister } from "@/mersenne"; +import { fisherYates } from "@/fisheryates"; export async function getSleepStationSongs(): Promise { const m = new SIMDMersenneTwister(); @@ -16,9 +17,10 @@ export async function getSleepStationSongs(): Promise { title: title, image: `https://lofi-cdn.srizan.dev/sleep/thumbs/${file.replace('.opus', '')}.webp`, label: 'Chilled Cat', + duration: 0, // TODO: get duration for all songs and put them in list.json }; }) as Song[]; - const shuffled = mapped.sort(() => 0.5 - m.random()).slice(0, 5); + const shuffled = fisherYates(m, mapped).slice(0, 5); return shuffled; } diff --git a/src/lib/types.ts b/src/lib/types.ts index b67f9e5..1e97caa 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -3,9 +3,9 @@ export interface Song { title: string; endpoint: string; image: string; + duration: number; // not really used right now label?: string; // optional record label - spotifyId?: string; // TODO: enforce in the future for all spotify scraped stations - duration?: number; // TODO: enforce in all stations + spotifyId?: string; // TODO: enforce in the future for all spotify scraped stations, unused atm. } export interface CHSong {