The function like that would be very simple:
function getColorNotSafe(languaje){
return colors[languaje].color;
}
BUT is not safe.
Let's see:
Here ALL GOOD
var colors = {
'1C Enterprise': {
'color': '#814CCC',
'url': 'https://github.com/trending?l=1C-Enterprise'
},
'ABAP': {
'color': '#E8274B',
'url': 'https://github.com/trending?l=ABAP'
},
'ActionScript': {
'color': '#882B0F',
'url': 'https://github.com/trending?l=ActionScript'
},
'Ada': {
'color': '#02f88c',
'url': 'https://github.com/trending?l=Ada'
}
};
console.log(getColorNotSafe("Ada"));
function getColorNotSafe(languaje){
return colors[languaje].color;
}
Here NOT ALL GOOD
The problem is that this function allows us to pass anything. Who will control that? Suppose you try to find Ada5
:
var colors = {
'1C Enterprise': {
'color': '#814CCC',
'url': 'https://github.com/trending?l=1C-Enterprise'
},
'ABAP': {
'color': '#E8274B',
'url': 'https://github.com/trending?l=ABAP'
},
'ActionScript': {
'color': '#882B0F',
'url': 'https://github.com/trending?l=ActionScript'
},
'Ada': {
'color': '#02f88c',
'url': 'https://github.com/trending?l=Ada'
}
};
console.log(getColorNotSafe("Ada5"));
function getColorNotSafe(languaje){
return colors[languaje].color;
}
Here BEST
Then, it is convenient to write a safe function, that returns at least null
if it does not find the property that is happening to it:
var urlGit='https://github.com/trending?l=';
var colors = {
'1C Enterprise': {
'color': '#814CCC',
'url': urlGit+'1C-Enterprise'
},
'ABAP': {
'color': '#E8274B',
'url': urlGit+'ABAP'
},
'ActionScript': {
'color': '#882B0F',
'url': urlGit+'ActionScript'
},
'Ada': {
'color': '#02f88c',
'url': urlGit+'Ada'
}
};
console.log(getColor("Ada"));
console.log(getColor("Ada5"));
function getColor(languaje) {
var resultado=colors.hasOwnProperty(languaje) ? colors[languaje].color : null;
return resultado;
}
Another plus
Note that an interesting re-game could be made for the url
: it would be to combine the received parameter with the variable urlGit
... I have not dared to do so because the values are not normalized in the case of the first option. I put this note to open that possibility, looking to simplify the code, making it less repetitive.