You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否在semver函数中使用Ramda的R.__占位符?

问题:Ramda占位符R.__与semver.lt结合不生效的原因?

要将newRecord按semver包定义的排序规则插入数组的正确位置,测试数据如下:

const semvers = ["5.100.0-rc.0", "5.97.3", "5.97.1"];
const newRecord = "5.97.2";

预期结果:

result = ["5.100.0-rc.0", "5.97.3", "5.97.2", "5.97.1"];

已实现能得到正确结果的代码:

const semvers = ["5.100.0-rc.0", "5.97.3", "5.97.1"];
const newRecord = "5.97.2";

const indexResult = R.findIndex(x => semver.lt(x, newRecord))(semvers);
const result = R.insert(indexResult, newRecord, semvers)

随后尝试用R.__替换x,代码如下但未生效:

const indexResult = R.findIndex(semver.lt(R.__, newRecord))(semvers);

疑问:是不是因为semver.lt不是柯里化函数导致的?


回答

没错,问题核心就是semver.lt不是Ramda风格的柯里化函数。

Ramda的R.__占位符只对Ramda自身的柯里化函数生效——这类函数会自动识别占位符,延迟参数传入并返回新的函数。但semver.lt是普通的JavaScript函数,它不会处理R.__,只会把它当作一个普通参数传入,自然达不到你想要的“用占位符指代后续数组元素”的效果。

要解决这个问题,有两种简单方式:

  • 方式一:用R.curry把semver.lt转换为柯里化函数,这样就能正常使用R.__占位符了:
const curriedSemverLt = R.curry(semver.lt);
const indexResult = R.findIndex(curriedSemverLt(R.__, newRecord))(semvers);
  • 方式二:继续使用箭头函数包裹,这也是最直接且不易出错的写法,就是你最初实现的版本。

内容的提问来源于stack exchange,提问作者Isaac

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 22:33:33