如果使用ES6或ES7阻止条件,则减少

时间:2018-03-10 14:14:22

标签: javascript ecmascript-6

我写了这个if if block但是我并不完全满意。有没有办法进一步减少线路,仍然可以利用ES6或ES7读取?

export default function validation(str, props) {
  const {
    length, minLength, maxLength, required,
  } = props;

  if ((required && str.length === 0) || // check string length only if required is defined
    (length && str.length !== length) || // check if string length matches only if length is defined
    (minLength && str.length < minLength) || // check if less than minLength only if minLength is defined
    (maxLength && str.length > maxLength)) { // check if greater than maxLength only if maxlength is defined
    return false;
  }
  return true;
}

3 个答案:

答案 0 :(得分:4)

由于if表达式应该是布尔值,并且函数根据它返回布尔值,因此可以省略if

可以通过引入中间变量来使代码自我记录:

function validation(str, props) {
  const {
    length, minLength, maxLength, required,
  } = props;

  const isEmpty = (required && str.length === 0);
  const isDifferentLength = (length && str.length !== length);
  ...

  return !(isEmpty || isDifferentLength || ...);
}

答案 1 :(得分:2)

您可以通过解构道具来缩短功能。您也可以直接返回布尔结果。

export default function validation(str, { length, minLength, maxLength, required }) {

  return !((required && str.length === 0)        ||
           (length && str.length !== length)     ||
           (minLength && str.length < minLength) ||
           (maxLength && str.length > maxLength))
}

如果您使用箭头功能,您也可以删除返回。

const validation = (str, { length, minLength, maxLength, required }) =>
  !((required && str.length === 0)        ||
    (length && str.length !== length)     ||
    (minLength && str.length < minLength) ||
    (maxLength && str.length > maxLength))

答案 2 :(得分:1)

我发现最简洁的方法是使用对象解构默认值:

function validate(str, props) {
  const { length = str.length, minLength = length, maxLength = length, required } = props; 

  return (!required || !!str.length) && str.length >= minLength && str.length <= maxLength;
}