1import { get, writable } from 'svelte/store';
2
3/**
4 * Creates a persistent counter that is stored in a file
5 * @param fileName The name of the file to store the count in
6 * @param initialValue The initial value if the file doesn't exist
7 * @returns An object with methods to get, increment, and set the count
8 */
9export const createFileCounter = async (filePath: string, initialValue: number = 0) => {
10 let countRaw: string | null = null;
11 try {
12 countRaw = await Deno.readTextFile(filePath);
13 } catch {}
14
15 const counter = writable(parseInt(countRaw ?? initialValue.toString()));
16
17 const saveToFile = async (value: number) => {
18 await Deno.writeTextFile(filePath, value.toString());
19 return value;
20 };
21
22 return {
23 get: () => get(counter),
24 increment: (amount: number = 1) => {
25 const currentValue = get(counter) + amount;
26 counter.set(currentValue);
27 return saveToFile(currentValue);
28 },
29 set: (value: number) => {
30 counter.set(value);
31 return saveToFile(value);
32 },
33 subscribe: counter.subscribe
34 };
35};