在lodash / ramda中有这些比较案例的替代方案吗?

时间:2017-05-25 09:37:06

标签: javascript lodash ramda.js

这是我的实施例子。

function comparator(values = [], matchValue, mapFn, reduceFn) {
  if (values.length === 0) {
    return undefined !== matchValue;
  }

  return values
    .map(mapFn)
    .reduce(reduceFn);
}

/**
 * const a = 1, b = 2, c = 3;
 * a === 1 || b === 1 || c === 1 // true
 * isEqualOr([1, 2, 3], 1) // true
 */
export const isEqualOr = (values, matchValue) => comparator(
  values,
  matchValue,
  value => value === matchValue,
  (prev, curr) => prev || curr
);
/**
 * a === 1 && b === 1 && c === 1 // false
 * isEqualAnd([1, 2, 3], 1) // false
 */
export const isEqualAnd = (values, matchValue) => comparator(
  values,
  matchValue,
  value => value === matchValue,
  (prev, curr) => prev && curr
);
/**
 * a !== 1 || b !== 1 || c !== 1 // true
 * isNotEqualOr([1, 2, 3], 1) // true
 */
export const isNotEqualOr = (values, matchValue) => comparator(
  values,
  matchValue,
  value => value !== matchValue,
  (prev, curr) => prev || curr
);
/**
 * a !== 1 && b !== 1 && c !== 1 // false
 * isNotEqualAnd([1, 2, 3], 1) // false
 */
export const isNotEqualAnd = (values, matchValue) => comparator(
  values,
  matchValue,
  value => value !== matchValue,
  (prev, curr) => prev && curr
);
  1. 你在日常工作中需要这样的工具吗?
  2. 你如何解决这个问题?
  3. 您对此实施有何看法?
  4. 对于这些情况,lodash / ramda库中有工具吗?

1 个答案:

答案 0 :(得分:1)

在Ramda中,我会使用allany,使用complement进行否定:

const isEqualOr = (values, matchValue) => any(equals(matchValue), values);

isEqualOr([1, 2, 3], 1); //=> true
isEqualOr([1, 2, 3], 5); //=> false

const isEqualAnd = (values, matchValue) => all(equals(matchValue), values);

isEqualAnd([1, 2, 3], 2); //=> false
isEqualAnd([2, 2, 2], 2); //=> true

// const isNotEqualOr = (values, matchValue) => any(complement(equals)(matchValue), values);
// or
const isNotEqualOr = complement(isEqualAnd);

isNotEqualOr([1, 2, 3], 2); //=> true
isNotEqualOr([2, 2, 2], 2); //=> false

// const isNotEqualAnd = (values, matchValue) => all(complement(equals)(matchValue), values);
// or
const isNotEqualAnd = complement(isEqualOr);

isNotEqualAnd([1, 2, 3], 2); //=> false
isNotEqualAnd([1, 2, 3], 5); //=> true

使这些无点变得相当容易,但我认为没有任何理由这样做。