Note that there are some explanatory texts on larger screens.

plurals
  1. POReturning nested object values based on function arguments
    primarykey
    data
    text
    <p>I'm trying to complete an exercise and somethings just not clicking. </p> <p>Here's the question: Could you write in JS (or Coffescript or any language that actually makes sense) a method getTranslation(lang, path) --> string that works the following way: You have this global object:</p> <pre><code>strings = { home: { intro: { en: 'Welcome', fr: 'Bienvenue' }, content: { explanation: { en: 'This is an interesting exercise', fr: 'C\'est un exercice intéressant', de: 'Es ist eine interesante Übung' }, contact: 'Contact', goodbye: { en: 'Goodbye', fr: 'Au revoir', es: 'Adios' } } } } </code></pre> <p>and</p> <pre><code>getTranslation('home.intro', 'fr') // =&gt; 'Bienvenue' getTranslation('home.content.contact', 'fr') // =&gt; 'Contact' getTranslation('home.intro', 'es') // =&gt; 'Welcome' getTranslation('home.content.goodbye') // =&gt; 'Goodbye' getTranslation('unvalid.path','en') // =&gt; '' </code></pre> <p>So the first argument is a string that describes the path through the keys separated by a dot (not dots in keys assumed), and the second argument is the language, which falls back to 'en' if not provided or nonexistent (we also assume that at the end of every branch, either the 'en' keys exists, or it is a single string like in home.content.contact).</p> <p>Here's my answer that I've come up with so far but I know I'm doing something wrong because nothings being returned.</p> <pre><code>function getTranslation (path, lang) { lang = lang || "en"; var strings = { home: { intro: { en: 'Welcome', fr: 'Bienvenue' }, content: { explanation: { en: 'This is an interesting exercise', fr: 'C\'est un exercice intéressant', de: 'Es ist eine interesante Übung' }, contact: 'Contact', goodbye: { en: 'Goodbye', fr: 'Au revoir', es: 'Adios' } } } if (path == 'home.content.contact') { return strings.path; } else if (path == 'unvalid.path') { return ''; } else { return strings.path.lang; } } getTranslation('home.intro', 'fr'); // =&gt; 'Bienvenue' getTranslation('home.content.contact', 'fr'); // =&gt; 'Contact' getTranslation('home.intro', 'es'); // =&gt; 'Welcome' getTranslation('home.content.goodbye'); // =&gt; 'Goodbye' getTranslation('unvalid.path','en'); // =&gt; '' </code></pre> <p>Thank you to anyone willing to help.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload