From 38431710cfb1cc1ffd7297085d069be1328f083b Mon Sep 17 00:00:00 2001 From: Ruben Beltran del Rio Date: Sun, 29 Aug 2021 21:49:37 +0200 Subject: Add project --- src/lib/stores/prompt.js | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/lib/stores/prompt.js (limited to 'src/lib/stores') 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() {}; + }); +}; -- cgit