From 4094b45b58ac01a6045e92db06e9b558c48f66ab Mon Sep 17 00:00:00 2001 From: Logan Dam Date: Sun, 5 Jan 2025 18:32:18 +0100 Subject: [PATCH] prefill carriage number --- frontend/src/routes/fun/carriage/+page.svelte | 37 +++++++++++++++---- 1 file changed, 29 insertions(+), 8 deletions(-) diff --git a/frontend/src/routes/fun/carriage/+page.svelte b/frontend/src/routes/fun/carriage/+page.svelte index ed623b1..bda7f9a 100644 --- a/frontend/src/routes/fun/carriage/+page.svelte +++ b/frontend/src/routes/fun/carriage/+page.svelte @@ -23,15 +23,29 @@ } ]; let target = $state(15); + let firstLoad = $state(true); let carriageNumber: number = $state(); + let terms: number[] = $derived(getTerms(carriageNumber)); - let terms: number[] = $derived( - (carriageNumber || '') - .toString() - .split('') - .map((c) => +c) - ); - let options: string[][] = $derived.by(() => { + let options: string[][] = $derived(getOptions(target, terms)); + + $effect(() => { + while (firstLoad && !options.length) { + let n = getRandomCarriageNumber(); + let t = getTerms(n); + if (getOptions(target, t).length) { + carriageNumber = n; + firstLoad = false; + break; + } + } + }); + + function getRandomCarriageNumber() { + return Math.floor(Math.random() * (999999 - 100000 + 1) + 100000); + } + + function getOptions(target: number, terms: number[]): string[][] { const ret = []; const stack: [{ terms: number[]; ops: (string | number)[] }] = [{ terms, ops: [terms[0]] }]; while (stack.length) { @@ -55,7 +69,14 @@ } return ret; - }); + } + + function getTerms(n: number) { + return (n || '') + .toString() + .split('') + .map((c) => +c); + }