HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

replace() for translating color names

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
translatingcolorreplacenamesfor

Problem

I have some code to translate some color names, and this is what I did, quick and dirty.
But I'm guessing there might be some function to replace arrays with arrays maybe, like in PHP, where you can have str_replace($array_of_colors, $replace_array_of_colors, $colors);.

var color = colors[c].replace(/sort/i, "Black");
color = color.replace(/brun/i, "Brown");
color = color.replace(/hvit/i, "White");
color = color.replace(/oransje/i, "Orange");
color = color.replace(/gul/i, "Yellow");
color = color.replace(/beige/i, "Beige");
color = color.replace(/Mørk/i, "Dark");
color = color.replace(/Rosa/i, "Pink");
color = color.replace(/rød/i, "Red");
color = color.replace(/Blå/i, "Blue");
color = color.replace(/grå/i, "Gray");
color = color.replace(/Lys/i, "Light");
color = color.replace(/lilla/i, "Purple");

Solution

You're mixing up data and logic. Separate your replaces into an associative array and iterate over that instead: (My JS is extremely bad, so this will be more pseudocode-ish)

var associations;
associations['/brun/i'] = "Brown";
associations['/sort/i'] = "Black";
//add all the other associations and then

associations.forEach(runReplace);

function runReplace(value, regex, array) {
   color.replace(regex, value);
}


Additionally I suggest you (just like me here) use the Array.prototype.forEach() when iterating over your colors

Code Snippets

var associations;
associations['/brun/i'] = "Brown";
associations['/sort/i'] = "Black";
//add all the other associations and then

associations.forEach(runReplace);

function runReplace(value, regex, array) {
   color.replace(regex, value);
}

Context

StackExchange Code Review Q#70073, answer score: 10

Revisions (0)

No revisions yet.