重构对象键以避免重言式

时间:2019-03-06 13:04:08

标签: javascript javascript-objects

我有一个对象,用于获取元素的正确位置值。 如何优化此对象以避免关键部门的重言式?

当前我的对象如下所示:

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];
}

我不知道如何重构它。

1 个答案:

答案 0 :(得分:2)

要实现此目的,您可以使用switch语句:

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));