aboutsummaryrefslogtreecommitdiff
path: root/src/lib/stores/courts.svelte.js
blob: 768bb35fdce6b25ab4efa0d0538c08a1b7b034aa (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { createCourt } from "../logic/players.js";
import { randomStatus } from "../logic/random.js";

const STORAGE_KEY = "Court";
const COURT_COUNT = 12;

function loadInitialCourts() {
  const stored = JSON.parse(localStorage.getItem(STORAGE_KEY));
  if (stored && stored.length > 0) {
    return stored.map((c) => createCourt(Number(c.id), Boolean(Number(c.status))));
  }
  return Array.from({ length: COURT_COUNT }, (_, i) => createCourt(i, randomStatus()));
}

let courts = $state(loadInitialCourts());

function persist() {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(courts));
}
if (!localStorage.getItem(STORAGE_KEY)) persist();

export function getCourts() {
  return courts;
}

export function activeCourts() {
  return courts.filter((c) => c.status);
}

export function inactiveCourts() {
  return courts.filter((c) => !c.status);
}

export function toggleCourt(id) {
  const court = courts.find((c) => c.id === id);
  if (!court) return;
  court.status = !court.status;
  persist();
}