编程语言
首页 > 编程语言> > javascript-Ramda-按索引分区

javascript-Ramda-按索引分区

作者:互联网

如何使用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>

解决方法:

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

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

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

那次翻转使我意识到要删除的参数可能是错误排列的.

更新资料

瑜伽士指出,期望的响应可能是[‘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']]

标签:ramda-js,javascript
来源: https://codeday.me/bug/20191025/1925740.html