I have an object that I use to get proper position values for my elements. How do I optimize this object to avoid tautology in key department?
Currently my object looks like this below:
function animPos(animName, position) {
const availibleValues = {
onLoadAnim: position,
greetingAnim: position,
textAnim: currentAnim === AnimRight ? 0 : 505,
inputAnim: currentAnim === AnimRight ? 0 : 505,
evaluationAnim: currentAnim === AnimRight ? 0 : 505,
testAnim: currentAnim === AnimRight ? 0 : 505,
passedAnim: currentAnim === AnimRight ? 0 : 505,
default: 251.5,
};
return availibleValues[animName];
}
I have no idea how to refactor this.
To achieve this you could use a switch
statement:
var currentAnim = 1; // needed to make sample work
var AnimRight = 1;
function animPos(animName, position) {
switch (animName) {
// first group
case "onLoadAnim":
case "greetingAnim":
return position;
// second group
case "textAnim":
case "inputAnim":
case "evaluationAnim":
case "testAnim":
case "passedAnim":
return currentAnim === AnimRight ? 0 : 505;
};
// default
return 251.5;
}
console.log("inputAnim -> " + animPos("inputAnim", 15));
console.log("greetingAnim -> " + animPos("greetingAnim", 15));
console.log("unknown -> " + animPos("unknown", 15));