ramda findIndex 有间隙
ramda findIndex with gaps
我有下面的代码,我想在其中填写id
,所以我想写这样的东西:
const data = [
{ id: 'some-id' },
{ id: 'some-other-id' },
{ id: 'third-id' },
];
const tabIndex = R.findIndex(R.propEq('id', R.__))(data);
所以我可以这样使用它tabIndex('third-id')
,但这不是一个函数。
我想念或混淆了什么?
以下作品
const tabIndex = (id) => R.findIndex(R.propEq('id', id))(data);
但我想,这就是 R.__
差距函数的意义所在。
我自己仍在努力掌握这种黑暗艺术,但我认为问题在于 R.findIndex
需要谓词(函数/断言)作为参数,并且不区分谓词和常规柯里化函数作为输入。
为了解决这个问题,可以编写一个新函数(从右到左求值):
const data = [
{ id: 'some-id' },
{ id: 'some-other-id' },
{ id: 'third-id' }
];
const tabIndex = R.compose(R.findIndex(R.__, data), R.propEq('id'));
console.log(tabIndex('third-id')); // 2
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.24.1/ramda.min.js"></script>
旁注: R.__
占位符会自动推断缺少最右边的参数 - 例如R.propEq('id')
和 R.propEq('id', R.__)
是等价的。
我认为到目前为止最简单的方法是
const matchId = (id, data) => R.findIndex(R.propEq('id', id), data);
matchId('third-id', data); //=> 2
如果你真的想免分,Ramda 提供了几个函数来帮助,比如 useWith
and converge
(for which one can often substitute lift
。)这个需要 useWith
:
const matchId = R.useWith(findIndex, [R.propEq('id'), R.identity]);
matchId('third-id', data); //=> 3
但我发现第一个版本更具可读性。您可以在 Ramda REPL.
上找到两者
请注意 。 R.__
占位符主要用于显示 之间 您提供的参数之间的差距;作为最后一个参数,它什么都不做。
我有下面的代码,我想在其中填写id
,所以我想写这样的东西:
const data = [
{ id: 'some-id' },
{ id: 'some-other-id' },
{ id: 'third-id' },
];
const tabIndex = R.findIndex(R.propEq('id', R.__))(data);
所以我可以这样使用它tabIndex('third-id')
,但这不是一个函数。
我想念或混淆了什么?
以下作品
const tabIndex = (id) => R.findIndex(R.propEq('id', id))(data);
但我想,这就是 R.__
差距函数的意义所在。
我自己仍在努力掌握这种黑暗艺术,但我认为问题在于 R.findIndex
需要谓词(函数/断言)作为参数,并且不区分谓词和常规柯里化函数作为输入。
为了解决这个问题,可以编写一个新函数(从右到左求值):
const data = [
{ id: 'some-id' },
{ id: 'some-other-id' },
{ id: 'third-id' }
];
const tabIndex = R.compose(R.findIndex(R.__, data), R.propEq('id'));
console.log(tabIndex('third-id')); // 2
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.24.1/ramda.min.js"></script>
旁注: R.__
占位符会自动推断缺少最右边的参数 - 例如R.propEq('id')
和 R.propEq('id', R.__)
是等价的。
我认为到目前为止最简单的方法是
const matchId = (id, data) => R.findIndex(R.propEq('id', id), data);
matchId('third-id', data); //=> 2
如果你真的想免分,Ramda 提供了几个函数来帮助,比如 useWith
and converge
(for which one can often substitute lift
。)这个需要 useWith
:
const matchId = R.useWith(findIndex, [R.propEq('id'), R.identity]);
matchId('third-id', data); //=> 3
但我发现第一个版本更具可读性。您可以在 Ramda REPL.
上找到两者请注意 R.__
占位符主要用于显示 之间 您提供的参数之间的差距;作为最后一个参数,它什么都不做。