javascript - Ramda - 按索引分区

标签 javascript ramda.js

如何使用 RamdaJS 通过 index 实现 partition

/*
 * @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>

最佳答案

一个相当简单的无点解决方案是

const partitionByIndex = converge(pair, [compose(of, nth), flip(remove)(1)])

partitionByIndex(2, ['a', 'b', 'c', 'd', 'e']) //=> [['c'], ['a', 'b', 'd', 'e']]

flip 让我意识到 remove 的参数可能顺序错误。

更新

Yogi 指出期望的响应可能是 ['c', ['a', 'b', 'd', 'e']] 而不是上面的结果:[['c'], ['a', 'b', 'd', 'e']]。如果是这样的话,这段代码可以变得更简单:

const partitionByIndex = converge(pair, [nth, flip(remove)(1)])

partitionByIndex(2, ['a', 'b', 'c', 'd', 'e']) //=> ['c', ['a', 'b', 'd', 'e']]

关于javascript - Ramda - 按索引分区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51398136/

相关文章:

javascript - jQuery Accordion - 缺少什么?

javascript - Ramda,数组相等而不考虑顺序

ramda.js - 使用 Ramda 简化数组计算

javascript - 格式化使用来自 SharePoint 的 REST ajax 调用获取的日期

javascript - 将 select 标签的选项的 json 数据存储在变量中

javascript - 如何使CSS宽度属性等于数学表达式的结果

javascript - 如何正确使用 Ramda/JS 编写函数

javascript - 无限循环 slider 概念

javascript - lambda : replace NULL values in json array

javascript - 函数式 Ramda 传递函数参数超出范围