无法将 parseInt 用作 ramdajs 的 ifElse 的 onTrue 或 onFalse 函数

not able to use parseInt as a onTrue or onFalse function for ifElse of ramdajs

我使用 ramdajs 的 ifElse 来读取查询参数,如下所示。

const page = ifElse(
  identity,
  Number.parseInt,
  always(1)
)(this.ctx.request.query.page);

没用。页面被记录为一个函数。 但是,我确实找到了让它发挥作用的方法。我将 parseInt 包装为一个普通函数

const page = ifElse(
  identity,
  (s) => Number.parseInt(s),
  always(1)
)(this.ctx.request.query.page);

然后就成功了。 它们不一样吗?

这是 ramdajs repl 的结果:repl result

Then it worked. Aren't they the same?

不对,有两点不同

  1. Number.parseInt 需要两个参数,因此具有 2 个参数,而您定义的箭头函数具有 1 个参数。

根据 curryN 的来源,如果 arity 为 1,则执行方法。

解决方案,将Number.parseInt替换为Number应该可行working link

  1. Number.parseInt 是一个 函数引用 ,它有自己的 thisarguments 对象,但是 箭头函数 没有自己的参数,因此有 difference between how apply and call work on arrow function

gurvinder372 的回答给出了最好的解决方案。 (另一种方法是将 Number.parseInt 包装在 R.unary 中。)

发生这种情况的原因是 ifElse returns 柯里化函数具有提供给它的三个函数中最大的元数(谓词、ifTrue 和 ifFalse。)由于 parseInt 的元数为 2,而不像其他函数那样为 1 或 0,因此返回的函数的元数为 2。

此行为 discussed recently 在 Ramda 问题列表中。