phrasebook.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * This class repesents phrasebook, which is something like dictionary,
  3. * but not for words, for all phrases in app. It give functions which
  4. * could find and translates phrases.
  5. */
  6. class phrasebook {
  7. #collection;
  8. /**
  9. * This create new phrasebook, which given collection of phrqses.
  10. *
  11. * @param {Map} collection - Collection of phrases to translate from.
  12. */
  13. constructor(collection) {
  14. if (!(collection instanceof Map)) {
  15. throw new Error("Phrasebook must be indialized with map.");
  16. }
  17. this.#collection = collection;
  18. }
  19. /**
  20. * This function translate phrase to lang which coresponds to the
  21. * phrasebook. It try to find given phrase in the phrasebook, and
  22. * when find it, return that. In the other way, when phrase could
  23. * not being fount, write warning to the debug console, and return
  24. * phrase in given not translated form. When phrase in phrasebook
  25. * is not string, then also return not translated phrase and
  26. * report it into developer console.
  27. *
  28. * @param {string} phrase - Phrase to translate.
  29. * @return {string} Translated phrase.
  30. */
  31. get(phrase) {
  32. if (typeof(phrase) !== "string") {
  33. throw new Error("Phrase to translate must be string.");
  34. }
  35. if (this.#collection.has(phrase)) {
  36. const translated = this.#collection.get(phrase);
  37. if (typeof(translated) !== "string") {
  38. console.error("Result for \"" + phrase + "\" is not string.");
  39. return phrase;
  40. }
  41. return translated;
  42. }
  43. console.warn("Could not find \"" + phrase + "\" in phrasebook.");
  44. return phrase;
  45. }
  46. }
  47. exports.phrasebook = phrasebook;