]>
Commit | Line | Data |
---|---|---|
c0d27c05 RBR |
1 | import { readable } from 'svelte/store'; |
2 | import { browser } from '$app/env'; | |
3 | import { conjugate, pluralize } from '$lib/grammar'; | |
4 | ||
5 | const internals = { | |
6 | kVersion: '1:', // in case we need to force a re-fetch | |
7 | kHost: import.meta.env.VITE_PUBLIC_BASE_PATH || 'http://localhost:3000', | |
8 | kDataPrefix: '/data/', | |
73d2a492 RBR |
9 | kVerbsPath: 'verbs.json', |
10 | kNounsPath: 'nouns.json', | |
c0d27c05 RBR |
11 | |
12 | async get(path) { | |
13 | ||
14 | const targetFile = internals.kHost + internals.kDataPrefix + path; | |
15 | const data = browser && localStorage.getItem(internals.kVersion + targetFile); | |
16 | ||
17 | if (data) { | |
18 | return JSON.parse(data); | |
19 | } | |
20 | ||
21 | let newData = await (await fetch(targetFile)).json(); | |
22 | browser && localStorage.setItem(internals.kVersion + targetFile, JSON.stringify(newData)); | |
23 | ||
24 | return newData; | |
25 | }, | |
26 | ||
27 | random(list) { | |
28 | ||
29 | return list[Math.floor(Math.random() * list.length)]; | |
30 | } | |
31 | }; | |
32 | ||
33 | export const getInsult = function () { | |
34 | ||
35 | return readable(null, function (set) { | |
36 | ||
37 | (async function() { | |
38 | ||
39 | const verbs = await internals.get(internals.kVerbsPath); | |
40 | const nouns = await internals.get(internals.kNounsPath); | |
41 | ||
42 | const verb = await conjugate(internals.random(verbs)); | |
43 | const noun = pluralize(internals.random(nouns)); | |
44 | ||
45 | set(`${verb} ${noun}`.toLowerCase()); | |
46 | })(); | |
47 | ||
48 | return function stop() {}; | |
49 | }); | |
50 | }; |