Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ramda findIndex with gaps

Tags:

ramda.js

I have the following code where I want to fill in the id, so I'm thinking to write something like this:

const data = [
 { id: 'some-id' },
 { id: 'some-other-id' },
 { id: 'third-id' },
];

const tabIndex = R.findIndex(R.propEq('id', R.__))(data);

So I can use it like this tabIndex('third-id'), but this is not a function. What do I miss or confuse with this?

The following works

const tabIndex = (id) => R.findIndex(R.propEq('id', id))(data);

But I thought, that is the point of R.__ gaps function.

like image 734
eenagy Avatar asked Nov 30 '25 12:11

eenagy


2 Answers

I think that by far the simplest way to do this is

const matchId = (id, data) => R.findIndex(R.propEq('id', id), data);
matchId('third-id', data); //=> 2

If you really want to make this points-free, Ramda offers several functions to help, such as useWith and converge (for which one can often substitute lift.) This one would take useWith:

const matchId = R.useWith(findIndex, [R.propEq('id'), R.identity]);
matchId('third-id', data); //=> 3

But I find the first version much more readable. You can find both on the Ramda REPL.


Do pay attention to the side note from Emissary. The R.__ placeholder is essentially used to show gaps between the arguments you supply; as a final argument it doesn't do anything.

like image 122
Scott Sauyet Avatar answered Dec 03 '25 00:12

Scott Sauyet


I'm still trying to master this dark art myself but I think the issue is that R.findIndex expects a predicate (a function / assertion) as an argument and does not differentiate between predicates and regular curried functions as input.

To resolve this a new function can be composed (evaluated right to left):

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>

Side Note: the R.__ placeholder is inferred automatically for missing right-most arguments - e.g. R.propEq('id') and R.propEq('id', R.__) are equivalent.

like image 20
Emissary Avatar answered Dec 03 '25 00:12

Emissary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!