Translate all app texts in multiple langs - JavaScript - javascript

I have implemented my app in English, and I am looking for a way to cover 3 other langs.
I have thought to create a module langs.js
and then, create a map like this one:
const texts = {
"spanish": {
"home": {
"header": "Hello",
"footer": "World"
},
...
},
...
}
But... is that the way? Any ideas? This is my fist time doing something like this.

Related

Can't style element correctly in if/else codeblock

I have some data from dummy back-end for example:
[
{
"title": "title title 0",
"date": "22/09/2015",
"author": "author00",
"langs": [
"react",
"javascript"
]
},
{
"title": "title 1",
"date": "09/11/2012",
"author": "author188",
"langs": [
"angular",
"vue"
]
}],
I try to stylize "langs" array by it's first element, example:
const posts = this.state.posts.map(post => {
if (post.tags[0].startsWith("react")){
post.style.backgroundColor = "red";
}
}
I think 'if' statement is correct but I don't know what to try in codeblock.
when I try to log in console somewhat it is ok.
but many things on this case depends on what is the first [0] element in the array...
for example, if first element contains 'angular' in cideblock many style options must be rearanged on red color, and when it contains 'react' the dominant style color in every case must be a blue color.
can you advice me generally what is the best solution for changing styles of lots of things with if/else statement?
Make a color map that defines colors for code tags like this:
const colorMap = { 'react': 'red', 'angular': 'blue' };
then use it like this:
const posts = this.state.posts.map(post => {
const tag = post.tags[0];
const color = colorMap[tag];
post.style.backgroundColor = color;
});

JSON, node.js: access classes via its name (String)

Here's my situation, I have a JSON that looks somewhat like this:
{
"items": [{
"type": "condition",
"data": {
"type": "comparison",
"value1": {
"source": "MyType1",
"component": "Attribute1"
},
"value2": {
"source": "MyType2",
"component": "Attribute2"
},
"operator": "gt"
}
},
{
"type": "then",
"data": {
"result": "failed",
"message": "value1 is too high"
}
}
]
}
and would want it to translate to:
if (MyType1.Attribute1 > MyType2.Attribute2) {
result = "failed";
console.log("value1 is too high");
}
Now my problem is, I don't know how I would translate the entries of value1 and value2 to actual code, or rather, how I could access the Object MyType1(maybe through something like getAttribute("MyType1")).
Since I am going to have a whole bunch of sources which each have different components, I cant really write a huge dictionary. Or I would like to avoid it.
The goal is to allow creating if - then - statements via some interactive UI, and I figured it'd be best to save that code as .json files. (Think rule management system).
So, TL,DR, How would I access a Class Attribute this.MyType, if I only have a String MyType to go from? And how would I access the value this.MyType.MyValue, if I get another String MyValue?
Thanks in advance.
Edit:
I'd really like to avoid using eval, for obvious reasons. And if I have to - I guess I would need to create Dictionaries for possible JSON Values, to validate the input?
You need some kind of parser. At first we need some way to store variables and maybe flags:
const variables = {};
var in = false;
Then we go through the code and execute it:
for(const command of items){
switch( command.type ){
case "condition":
//...
case "then":
//...
}
}
To access a variable we can simply do
var current = variables[ identifier ];
To store its the other way round:
variables[ identifier ] = current;

Limiting fields returned by mongo dynamically

I use Meteor to query a mongo collection. It has for example the following entry:
{
"_id": "uCfwxKXyZygcWQeiS",
"gameType": "foobar",
"state": "starting",
"hidden": {
"correctAnswer": "secret",
"someOtherStuff": "foobar"
},
"personal": {
"Y73uBhuDq2Bhk4d8W": {
"givenAnswer": "another secret",
},
"hQphob8s92gbEMXbY": {
"givenAnswer": "i have no clue"
}
}
}
What I am trying to do now is:
don't return the values behind "hidden"
from the "personal" embedded document only return the values for the asking user
In code it would look something like this:
Meteor.publish('game', function() {
this.related(function(user) {
var fields = {};
fields.hidden = 0;
fields.personal = 0;
fields['personal.' + this.userId] = 1;
return Games.find({}, {fields: fields});
}, Meteor.users.find(this.userId, {fields: {'profile.gameId': 1}}));
}
Obviously this won't work, because MongoDB won't allow mixed includes and excludes. On the other hand, I cannot switch to "specify only the included fields", because they can vary from gameType to gameType and it would become a large list.
I really hope that you can help me out of this. What can I do to solve the problem?
Typical example of where to use the directly controlled publication features (the this.added/removed/changed methods).
See the second example block a bit down the page at http://docs.meteor.com/api/pubsub.html#Meteor-publish.
With this pattern you get complete control of when and what to publish.

Angular2 Uncaught ReferenceError: Class is not defined

I am learning Angular2 using JavaScript(No TypeScript) with the help of this video. The code worked fine, until I started using a service. It starts to give me the following error -
Uncaught ReferenceError: Class is not defined
I understand that Class is not defined in JavaScript, but I assume that it's a part of Angular2 library. Here's my complete app.js code -
(function() {
var Component = ng.core.Component;
var bootstrap = ng.platformBrowserDynamic.bootstrap;
var QuoteService = Class({
constructor:function () {
this.quotes = quotes;
},
getRandomQuote: function (params) {
var randomIndex = Math.floor(Math.random()*quotes.length);
return this.quotes[randomIndex];
}
});
var RandomQuoteComponent = Component({
selector:'random-quote',
template:'<em>{{quote.line}}</em> - {{quote.author}}'
})
.Class({
constructor:function () {
var quoteService = new QuoteService();
this.quote = quoteService.getRandomQuote();
}
});
var AppComponent = Component({
selector: 'my-app',
directives:[RandomQuoteComponent],
template:
'<h1>Random Quotes</h1>'+
'<p><random-quote></random-quote></p>'
})
.Class({
constructor: function () {
//empty
}
});
document.addEventListener('DOMContentLoaded',function () {
bootstrap(AppComponent);
})
var quotes = [
{
"line": "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.",
"author": "Brian W. Kernighan"
},
{
"line": "Walking on water and developing software from a specification are easy if both are frozen.",
"author": "Edward V Berard"
},
{
"line": "It always takes longer than you expect, even when you take into account Hofstadter's Law.",
"author": "Hofstadter's Law"
},
{
"line": "Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.",
"author": "Rick Osborne"
},
{
"line": "In theory, there is no difference between theory and practice. But, in practice, there is.",
"author": "Jan L. A. van de Snepscheut"
},
{
"line": "Measuring programming progress by lines of code is like measuring aircraft building progress by weight.",
"author": "Bill Gates"
},
{
"line": "There are 2 hard problems in computer science: cache invalidation, naming things, and off-by-1 errors.",
"author": "Leon Bambrick"
},
{
"line": "Nine people can't make a baby in a month.",
"author": "Fred Brooks"
},
{
"line": "If debugging is the process of removing software bugs, then programming must be the process of putting them in.",
"author": "Edsger Dijkstra"
},
{
"line": "The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time.",
"author": "Tom Cargill"
}
];
})();
This line var QuoteService = Class({...}); is responsible for this error. Any idea what could be going wrong in this case?
I think you should write as follows:
var Class = ng.core.Class;
var QuoteService = Class({ ...
https://angular.io/api/core/Class

Retrieving only the parent elements from firebase : Angularfire

The image shows the structure of my database.
I want to print 1, 2 ... (so on) i.e. the parent element names alone. But couldn't understand how to do that.
The Firebase Database is essentially one JSON object.
This object is in a tree structure. If you read from one location in the tree, you'll get each piece of data underneath it.
Take a look at this sample database.
{
"items": {
"1": {
"title": "Hi"
},
"2": {
"title": "Bye"
}
}
}
There is no way with the JavaScript SDK or AngularFire, to only read the parent keys of 1 and 2 under "items".
If you only want to read the parent keys, you'll need to create an index for them in the Firebase database.
{
"items": {
"1": {
"title": "Hi"
},
"2": {
"title": "Bye"
}
},
"itemKeys": {
"1": "Hi",
"2": "Bye"
}
}
Now you can create a reference at the itemKeys location and pass that to a $firebaseArray() or $firebaseObject().
var ref = new Firebase('<my-firebase-app>.firebaseio.com/itemKeys');
var syncArray = $firebaseArray(ref);
If you're concerned with keeping two separate data structures consistent, check out the client-side fan-out feature.
shallow=true
If you are using REST API add this to the end of your request url. Like this
https://docs-examples.firebaseio.com/rest/retrieving-data.json?shallow=true

Categories