I have a piano with 88 keys. "keys" are the event key "k" . I use handlebars and backbone so it is impossible to write thousands of lines here..
What I would like is, if there is any way to write the following code in fewer lines .. (I use Javascript and jQuery so both are ok) Thank you very much
if (document.getElementById('do').innerHTML) {
document.getElementById(keys).innerHTML = "C";
}
if (document.getElementById('re').innerHTML) {
document.getElementById(keys).innerHTML = "D";
}
if (document.getElementById('mi').innerHTML) {
document.getElementById(keys).innerHTML = "E";
}
if (document.getElementById('fa').innerHTML) {
document.getElementById(keys).innerHTML = "F";
}
if (document.getElementById('sol').innerHTML) {
document.getElementById(keys).innerHTML = "G";
}
if (document.getElementById('la').innerHTML) {
document.getElementById(keys).innerHTML = "A";
}
if (document.getElementById('si').innerHTML) {
document.getElementById(keys).innerHTML = "B";
}
if (document.getElementById('do2').innerHTML) {
document.getElementById(keys).innerHTML = "C";
}
if (document.getElementById('re2').innerHTML) {
document.getElementById(keys).innerHTML = "D";
}
if (document.getElementById('mi').innerHTML) {
document.getElementById(keys).innerHTML = "E";
}
CodePudding user response:
You can create a lookup of your mapping and using iterate through each pair of key and value check for condition and assign it to html.
const lookup = {do: 'C', re: 'D', mi: 'E', fa: 'F', sol: 'G', la: 'A', si: 'B', do2: 'C', re2: 'D'}
Object.entries(lookup).forEach(([key, val]) => {
if (document.getElementById(key).innerHTML) {
document.getElementById(keys).innerHTML = value;
}
});
CodePudding user response:
I am not sure of the exact use case, but this code can be optimized by a map and for-loop. The sample code is below.
Sample approach below:
const KEY_MAP = {
"do": "C",
"re": "D",
"mi": "E",
"fa": "F",
"sol": "G",
"la": "A",
"si": "B",
"do2": "C",
"re2": "D",
}
function updateDomLabelUsingKeyMap(keys) {
Object.keys(KEY_MAP).forEach(el => {
if (document.getElementById(el).innerHTML) {
document.getElementById(keys).innerHTML = KEY_MAP[el];
}
});
}
Call this updateDomLabelUsingKeyMap
function with the keys prop.
CodePudding user response:
yes you can with variable
const constVar = document.getElementById(keys);
if (document.getElementById('do').innerHTML)
{ constVar.innerHTML = "C"; }