简体   繁体   English

fp-ts 将数组拆分成多个分区

[英]fp-ts Split an array into multiple partitions

I'm new to fp-ts , and I was wondering whether there's a utility/pattern for splitting an array into multiple partitions based on another array of indices/keys, such that the regular functions eg map() and foldMap() would operate on the partitions (sub-arrays of the original array):我是fp-ts新手,我想知道是否有一种实用程序/模式可以根据另一个索引/键数组将一个数组拆分为多个分区,以便常规函数(例如map()foldMap()可以运行在分区上(原始数组的子数组):

const x = ["a", "b", "c", "d", "e", "f"];
const p = [0, 0, 1, 2, 1, 0];

const partition = (partion: number[]) => (x: any[]) => {
  return x.reduce((result, nextValue, index) => {
    if (!(partion[index] in result)) result[partion[index]] = [];
    result[partion[index]].push(nextValue);
    return result;
  }, {});
};

const xPartitioned = partition(p)(x);
const shout = (x: string) => x.toUpperCase() + `!`;

// Works as intended: { "0": ["A!", "B", "F!"], "1": ["C!", "E!"], "2": ["D!"] }
const res1 = R.map(A.map(shout))(xPartitioned); 

// Would like to be able to do something like:
const res2 = P.map(shout)(xPartitioned)

Is there any existing utility for this, or should I write my own aliases, eg:是否有任何现有的实用程序,或者我应该写我自己的别名,例如:

const P = { map: (callbackfn) => (partitioned) => R.map(A.map(callbackfn))(partitioned) }

No, there isn't any existing utility for this.不,没有任何现有的实用程序。 I would define my own like this:我会这样定义我自己的:

import {flow} from 'fp-ts/function';

const P = { map: flow(A.map, R.map)) };

flow is left-to-right function composition. flow是从左到右function组成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM