Javascript: 如何使用对象字面量代替 if 和 switch 语句来处理基于表达式的条件?

Javascript: How to use object literals instead of if and switch statements for expression-based conditions?

在javascript中,我想至少考虑为我的控制流使用嵌套对象文字树,而不是 if 语句、switch 语句等

下面是一个使用 if 语句的函数转换为使用对象文字的函数来完成相同功能的示例。

// if & else if
function getDrink (type) {
  if (type === 'coke') {
    type = 'Coke';
  } else if (type === 'pepsi') {
    type = 'Pepsi';
  } else if (type === 'mountain dew') {
    type = 'Mountain Dew';
  } else {
    // acts as our "default"
    type = 'Unknown drink!';
  }
  return type;
}

// object literal
function getDrink (type) {
  var drinks = {
    'coke': function () {
      return 'Coke';
    },
    'pepsi': function () {
      return 'Pepsi';
    },
    'Mountain Dew': function () {
      return 'Mountain dew';
    },
    'default': function () {
      return 'Unknown drink!';
    }
  };
  return (drinks[type] || drinks['default'])();
}

这在测试简单值时有效,但如何将以下 switch 语句转换为对象文字控制结构?

switch (true) {
  case (amount >= 7500 && amount < 10000):
    //code
    break;
  case (amount >= 10000 && amount < 15000):
    //code
    break;

  //etc...

一个小帮手usong Array.find可能会有用:

 const firstCase = (...cases) => value => cases.find(c=> c[0](value))[1];

可用作:

const dayTime = firstCase(
  [t =>  t < 5, "night"],
  [t => t < 12, "morning"],
  [t => t < 18, "evening"],
  [true, "night"]
);

console.log(dayTime(10)); // morning

这也适用于函数:

const greetAtTime = firstCase(
  [t => t < 10, name => `Good morning ${name}!`],
  [t => t > 18, name => `Good evening ${name}!`],
  [true, name => `Hello ${name}!`]
);

console.log(greetAtTime(12)("Jack"));

这似乎有效

const getValue = (value) => ({
  [value == 1]: 'Value is 1',
  [value > 1]: 'Value is greater than 1',
  [value < 1]: 'Value is less than 1',
})[true]

console.log(getValue(2));
console.log(getValue(-1)); 
console.log(getValue(-1+2)); // expect 'Value is 1'

可以用简单的方法

    const handlerPayment = () => { };
    const handlerFailure = () => { };
    const handlerPending = () => { };

    // Switch 
    switch (status) {
        case 'success':
            return handlerPayment();

        case 'failed':
            return handlerFailure();

        case 'pending':
            return handlerPending();
    
        default:
            throw Error('Status not recognize');
    }


    // Object
    const Handlers = {
        success: handlerPayment,
        failed: handlerFailure,
        pending: handlerPending,
    }
    
    const handler = Handlers[status];
    
    if (!handler) throw Error('Status not recognize');
    
    return handler();