As a beginner coder in js, I'd like to hear about further improvements of the following code, but nothing too advanced, please.
The program is meant to work the following way:
- A user inputs a color array like this one:
["blue", "green"]
- The code checks if those words are valid inputs (they should be found in a reference array of COLORS). This is done with
catchInvalid
function - If they are valid inputs, and so they are found in COLORS array, it gets the index of it. This is done in the
decodedValue
function
Example1:
COLORS= ["blue", "yellow", "red"]
User input: userColors=["yellow"]
returns index of yellow in COLORS i.e 1.
Example2:
COLORS= ["blue", "yellow", "red"]
User input: userColors=["yellow", "red"]
returns index 12 (index of yellow in colors*10 + index of red in colors (2)).
That's all. It's now working fine, but I wonder if you'd give any suggestions for improving the code.
const COLORS = ["black", "brown", "red", "orange", "yellow", "green", "blue", "violet", "grey", "white"];
//this will be the reference array
const catchInvalid = (color, COLORS) =>{
//checks if color is in COLORS (which is COLORS)
if(COLORS.indexOf(color)==-1){
return `not a ${color} in ${COLORS}`
}
else { }
}
const decodedValue = (colorArray) => {
//if previous 'color' is in the reference array, get the index of the color in COLORS.
let CODES=[];
if (colorArray.length==0){
return "Input a color value"
}
else if (colorArray.length==1){
catchInvalid(colorArray[0], COLORS)
return COLORS.indexOf(colorArray[0])
}
else {
for(let i=0; i<2;i++){
//only for the first 2 items in the array.
catchInvalid(colorArray[i], COLORS)
CODES.push(COLORS.indexOf(colorArray[i]))
}
return CODES[0]*10 + CODES[1];
}
}
console.log(decodedValue(["blue"]), decodedValue(["nothing"]), decodedValue(["blue", "green"]))