【问题标题】:Ramda - allPass returns true, even if one of the conditions is falseRamda - allPass 返回真,即使其中一个条件为假
【发布时间】:2020-09-11 08:00:49
【问题描述】:

我正在使用 Ramda 来清理我的代码。我有一些复杂的检查需要做。我决定使用 ramda 的 allPassanyPass 而不是 &&||

但我有一个问题。 AllPass,即使其中一个条件为假,也会返回true,而常规的 && 则返回假。

第一个检查是假的,第二个是真的。然而,这种奇怪的事情正在发生。

// Regulr &&, returns false
  const emptyView =
    R.contains(itemType, [IItemType.ONE, IItemType.TWO]) &&
    R.equals(mode, IViewMode.VIEW);

// Ramda allPass returns true
  const emptyView = R.allPass([
    R.contains(itemType, [IItemType.JSON, IItemType.AVRO]),
    R.equals(mode, IViewMode.VIEW),
  ]);

谁能给我解释一下为什么?我尝试了 Ramda 的两种变体。一个普通的数组,也调用了该函数,带有必要的信息,但没有运气。我做错了什么?

【问题讨论】:

  • 你确定第二个emptyView 不只是一个函数,因此总是计算为true
  • 我认为allPass 的行为类似于allPass([f, g, h]) //~-> (x, y) => f(x, y) && g(x, y) && (h(x, y)。生成函数中的参数数量是fgh 中最大的一个(理想情况下它们应该都相同),当然你实际传递给它的函数数量取决于你.但它不是替代foo && bar && baz。它接受函数并生成函数。

标签: javascript typescript evaluation ramda.js


【解决方案1】:

虽然第一个emptyView 实际上是布尔类型, 第二个只是一个函数(在 javascript 中总是计算为真)。

我认为以下是您真正需要的, 一个可以告诉您itemTypemode 是否正确的函数。

const IItemType = {
  JSON: 1,
  AVRO: 2
};

const IViewMode = {
 VIEW: 'view',
};

const fn = R.useWith(R.and, [
  R.contains(R.__, [IItemType.JSON, IItemType.AVRO]),
  R.equals(IViewMode.VIEW),
]);

console.log(
  'it should be true =>', 
  fn(1, 'view'),
);

console.log(
  'it should be false =>', 
  fn(1, 'something-but-view'),
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.js" integrity="sha512-3sdB9mAxNh2MIo6YkY05uY1qjkywAlDfCf5u1cSotv6k9CZUSyHVf4BJSpTYgla+YHLaHG8LUpqV7MHctlYzlw==" crossorigin="anonymous"></script>

【讨论】:

    猜你喜欢
    • 2022-07-21
    • 2017-09-17
    • 1970-01-01
    • 2012-05-28
    • 2020-03-08
    • 2014-11-24
    • 2015-03-21
    • 1970-01-01
    • 2014-09-07
    相关资源
    最近更新 更多