How can I achieve a partition by index using RamdaJS?
/*
* @param {number} index
* @param {[]} list
* @returns {[found, rest[]]} - array whose index 0 has the found element
* * and index 1 has the rest of the given list
*/
const partitionByIndex = (index, list) => {};
// this is what I got so far, but I really think it is too verbose
export const partitionByIndex = R.curry((i, cards) => R.pipe(
R.partition(R.equals(R.nth(i, cards))),
([found, rest]) => [R.head(found), rest],
)(cards));
const list = [1, 2, 3, 4, 5, 6, 7];
const index = 1;
const [found, rest] = partitionByIndex(index, list);
console.log({ found, rest });
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>
A fairly simple point-free solution is
const partitionByIndex = converge(pair, [compose(of, nth), flip(remove)(1)])
partitionByIndex(2, ['a', 'b', 'c', 'd', 'e']) //=> [['c'], ['a', 'b', 'd', 'e']]
And that flip makes me realize that the arguments to remove are probably mis-ordered.
Yogi pointed out that the desired response might be ['c', ['a', 'b', 'd', 'e']] rather than the result above: [['c'], ['a', 'b', 'd', 'e']]. And if that's the case, this code can become simpler:
const partitionByIndex = converge(pair, [nth, flip(remove)(1)])
partitionByIndex(2, ['a', 'b', 'c', 'd', 'e']) //=> ['c', ['a', 'b', 'd', 'e']]
Another approach to this is to R.take and R.drop around the R.nth element, such as:
R.converge(R.pair, [R.nth, (n, xs) => R.concat(R.take(n, xs), R.drop(n + 1, xs))])
Or without Ramda:
(n, xs) => [xs[n], xs.slice(0, n).concat(xs.slice(n + 1))]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With