aboutsummaryrefslogtreecommitdiff
path: root/src/lib/stores/prompt.js
blob: d0dc629ff1dc6de7f65d028b781f1b43045d19aa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { readable } from 'svelte/store';
import { browser } from '$app/env';

const internals = {
  kHost: import.meta.env.VITE_PUBLIC_BASE_PATH || 'http://localhost:3000',
  kDataPrefix: '/data/',
  kAdjectivesPath: '/adjectives.json',
  kNounsPath: '/nouns.json',

  async get(locale, path) {

    const shortLocale = locale.split('-')[0];
    const targetFile = internals.kHost + internals.kDataPrefix + shortLocale + path;
    const data = browser && localStorage.getItem(targetFile);

    if (data) {
      return JSON.parse(data);
    }

    let newData = await (await fetch(targetFile)).json();
    browser && localStorage.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() {};
  });
};