Good morning, I have the following code with the programming language javascript. And the thing is, I've been asked to optimize the function. Reduce the lines of code, that is, simplify it. Any suggestion? Thanks
function translate(box){
var row = box.substring(1,3);
var column = box.substring(0,1);
switch(column){
case "a":
return "1"+row;
case "b":
return "2"+row;
case "c":
return "3"+row;
case "d":
return "4"+row;
case "e":
return "5"+row;
case "f":
return "6"+row;
case "g":
return "7"+row;
case "h":
return "8"+row;
}
registraMoviment(box);
}
So far I haven't tried anything because I don't work with javascript or related languages, but I've been given this assignment anyway. Thank you
You can use this code:
const input = 'bRow';
function translate(box){
var row = box.substring(1,3);
var column = box.substring(0,1);
return (column.charCodeAt(0) - 96) + row;
}
console.log(translate(input));
For more info please read:
P.S. I didn't clearly understand the logic of registraMoviment(box); so I didn't include it in my example
Try this:
function translate(box){
var row = box.substring(1,3);
var column = box.substring(0,1);
var obj = {"a":"1", "b":"2", "c":"3", "d":"4", "e":"5", "f":"6", "g":"7", "h":"8" }
for(item in obj){
if(column === item){
return obj[item] + row
}
}
registraMoviment(box);
}
You can use the ASCII values of your letters to do this more mathy, but it certainly is much less readable.
function translate(box){
const row = box.substring(1,3);
const column = box.substring(0,1);
if(column >= "a" && column <= "h") {
const ASCII_VALUE_a = 97
// The +1 is to make it 1-indexed. The -ASCII_VALUE_a is to shift it so that "a" then becomes 1.
return `${column.charCodeAt() + 1 - ASCII_VALUE_a}${row}`
}
registraMoviment(box);
}
const box = "b13" // expected to become "213"
console.log(translate(box)) // 213
Another solution is Justinas' comment:
function translate(box){
const row = box.substring(1,3);
const column = box.substring(0,1);
const lookup = { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6: g: 7, h: 8 }
if(column in lookup) {
return lookup[column] + row
}
registraMoviment(box);
}
const box = "b13" // expected to become "213"
console.log(translate(box)) // 213