避免复杂的if语句

时间:2017-03-29 06:22:08

标签: javascript functional-programming

我有以下功能

const getVal = (type, a, b, val) => {
    if(type) {
        if(a && b) {
            return val;
        }else if(a) {
            return toPercent(val);
        }else{
            return undefined;
        }
    }
    return toPx(val);
}

有更好的表达方式吗?如何用函数式编程风格编写这样的代码

5 个答案:

答案 0 :(得分:2)

早期回归方法的另一个主张:

const getVal = (type, a, b, val) => {
    if(!type)
      return toPx(val);

    if(!a)
      return undefined;

    if(b)
      return val;             // (a && b)

    return toPercent(val);    // (a && !b)
}

这是一个单级比较,没有嵌套的if
但也许它很难去转换......

答案 1 :(得分:0)

你也可以尝试这样的事情:

  • 不是为if(type)创建阻止区段,而是将其设为if(!type),因为在这种情况下,您将返回一个函数调用。
  • 而不是a && b然后是a,只需检查a是否存在,然后检查b并相应地返回。如果a不存在,则无需检查b

三元运营商

const getVal = (type, a, b, val) => {
  if(!type) return toPx(val);
  return a ? (b ? val : toPercent(val) ) : undefined; 
}

if..else ladder

const getVal = (type, a, b, val) => {
  if(!type) return toPx(val);
  if(a){
    if(b) return val;
    return toPercent(val);
  }
}

答案 2 :(得分:0)

其他是不需要的。您可以在检查两个先前条件时返回。您还可以简明扼要地表达有关ab的决定:

const getVal = (type, a, b, val) => {
  if(type) {
    if(a) {
      if(b) {
        return val;
      }
      return toPercent(val);
    }
    return undefined;
  }
  return toPx(val);
}    

答案 3 :(得分:0)

通过功能编程,您可以使用一种称为currying的技术。所以你基本上有一个函数,它接受'type'并返回一个带'val'的新函数......等等。

const toPercent = (val) => {
  return 'toPercent: ' + val;
};
const toPX = (val) => {
  return 'toPx: ' + val;
};

const getValByFlags = (a, b, val) => {
  if (a) {
    return b 
      ? val
      : toPercent(val);
  } 
  return undefined;
}; 

const getValByType = (type) => {
  if (!type) return toPX;
  return (val) => {
    return (a, b) => {
      return getValByFlags(a, b, val);
    };
  };
};


let a = getValByType('a')(3)(true, true);
let b = getValByType()(3);
let c = getValByType('a')(3)(true, false);
let d = getValByType('a')(3)(false, false);

或一般

let getVal = getValByType(type);
let getValByConditions = getVal(val);
let resVal = type 
  ? getValByConditions(cond1, cond2)
  : getValByConditions;

答案 4 :(得分:0)

您可以使用三元运算符。像这样:

A

return type? ( a&&b ? val : ( a?  toPercent(val) : undefined )) : toPx(val);