Reputation: 1076
I tried to make this code shorter, but I don't have any idea of this.
First I tried this code
else if (language_url === 'html' || 'css' || c# || 'cplusplus) {
-Some Codes-
}
But this method cannot be used because, I have to save language_url
variable each different data.
For example
html to html5, css to css3, c# to csharp
So I remove this code and write different code, and it works but I want to make it shorter.
It's working but too many else if
codes looks bad.
Is there any idea to make it shorter?
[Wokring Code]
Repo.find({
'owner.login': userId
}, 'project_type login name language description', function (err, repoData) {
if (err) console.log(err);
for (let image of repoData) {
let language_url = image.language.toLowerCase();
if (image.language == 'null') {
image.imageUrl = `/images/app/${image.project_type}.png`;
} else if (language_url === 'html') {
language_url = 'html5'
} else if (language_url === 'css') {
language_url = 'css3'
} else if (language_url === 'c#') {
language_url = 'csharp'
} else if (language_url === 'c++') {
language_url = 'cplusplus'
} else if (image.language !== 'null') {
console.log(language_url)
} else {
// Need Amazon S3 image import code
}
image.imageUrl = `https://raw.githubusercontent.com/konpa/devicon/master/icons/${language_url}/${language_url}-original.svg`;
}
Upvotes: 0
Views: 52
Reputation: 4849
I believe a lookup table approach would make it clean.
let lookup = {
'css' : 'css3',
'html' : 'html5',
'c#': 'csharp'
}
let language_url = lookup[image.language.toLowerCase()]
The idea here is to replace the bulky if
conditions to do a lookup on the table, you can also do validation to check the availability of the property using the lookup.hasOwnProperty
method.
Upvotes: 2
Reputation: 370779
Use an object indexed by the input strings, whose values are the output strings:
const languages = {
html: 'html5',
css: 'css3',
'c#': 'csharp',
'c++': 'cplusplus',
}
Repo.find({
'owner.login': userId
}, 'project_type login name language description', function(err, repoData) {
if (err) return console.log(err);
for (const image of repoData) {
let language_url = image.language.toLowerCase();
if (image.language == 'null') {
image.imageUrl = `/images/app/${image.project_type}.png`;
} else if (languages[language_url]) {
language_url = languages[language_url];
} else {
// Need Amazon S3 image import code
}
Upvotes: 4