]> git.r.bdr.sh - rbdr/prompt/blob - src/lib/stores/prompt.js
59df711ae10762f4e18974b12008e5c6f269b03e
[rbdr/prompt] / src / lib / stores / prompt.js
1 import { readable } from 'svelte/store';
2 import { browser } from '$app/env';
3
4 const internals = {
5 kDataPrefix: 'http://localhost:3000/data/',
6 kAdjectivesPath: '/adjectives.json',
7 kNounsPath: '/nouns.json',
8
9 async get(locale, path) {
10
11 const shortLocale = locale.split('-')[0];
12 const targetFile = internals.kDataPrefix + shortLocale + path;
13 const data = browser && sessionStorage.getItem(targetFile);
14
15 if (data) {
16 return JSON.parse(data);
17 }
18
19 let newData = await (await fetch(targetFile)).json();
20 browser && sessionStorage.setItem(targetFile, JSON.stringify(newData));
21
22 return newData;
23 },
24
25 random(list) {
26
27 return list[Math.floor(Math.random() * list.length)];
28 }
29 };
30
31 export const getPrompt = function (locale) {
32
33 return readable(null, function (set) {
34
35 (async function() {
36
37 const adjectives = await internals.get(locale, internals.kAdjectivesPath);
38 const nouns = await internals.get(locale, internals.kNounsPath);
39
40 set(`${internals.random(nouns)}, ${internals.random(nouns)}, ${internals.random(adjectives)}`);
41 })();
42
43 return function stop() {};
44 });
45 };