diff options
| author | Ruben Beltran del Rio <ruben@unlimited.pizza> | 2021-08-29 21:49:37 +0200 |
|---|---|---|
| committer | Ruben Beltran del Rio <ruben@unlimited.pizza> | 2021-08-29 21:49:37 +0200 |
| commit | 38431710cfb1cc1ffd7297085d069be1328f083b (patch) | |
| tree | b28fba3eb891d8e1f383d4faa358ee7f067be93b /src/lib/stores | |
Add project
Diffstat (limited to 'src/lib/stores')
| -rw-r--r-- | src/lib/stores/prompt.js | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/src/lib/stores/prompt.js b/src/lib/stores/prompt.js new file mode 100644 index 0000000..59df711 --- /dev/null +++ b/src/lib/stores/prompt.js @@ -0,0 +1,45 @@ +import { readable } from 'svelte/store'; +import { browser } from '$app/env'; + +const internals = { + kDataPrefix: 'http://localhost:3000/data/', + kAdjectivesPath: '/adjectives.json', + kNounsPath: '/nouns.json', + + async get(locale, path) { + + const shortLocale = locale.split('-')[0]; + const targetFile = internals.kDataPrefix + shortLocale + path; + const data = browser && sessionStorage.getItem(targetFile); + + if (data) { + return JSON.parse(data); + } + + let newData = await (await fetch(targetFile)).json(); + browser && sessionStorage.setItem(targetFile, JSON.stringify(newData)); + + return newData; + }, + + random(list) { + + return list[Math.floor(Math.random() * list.length)]; + } +}; + +export const getPrompt = function (locale) { + + return readable(null, function (set) { + + (async function() { + + const adjectives = await internals.get(locale, internals.kAdjectivesPath); + const nouns = await internals.get(locale, internals.kNounsPath); + + set(`${internals.random(nouns)}, ${internals.random(nouns)}, ${internals.random(adjectives)}`); + })(); + + return function stop() {}; + }); +}; |