来自ramda实现的Javascript/Typescript分区函数



地狱,我正在为"ramda"中的R.partition实现工作。不用推!!仅使用map、filter、reduce函数。

这是我目前的实现方式:

partition = <T>(func : (param : T) => boolean, arr : T[]): T[][] => {
return [arr.filter((element : T) => func(element)), arr.filter((element : T) => !func(element))];   

}

示例:

const func = (x) => x%2 == 0

常量温度=[1,2,3,4,5,6,7,8,9];console.log(分区(func,tmep((;//=>[[2,4,6,8],[1,3,5,7,9]

双重过滤引入了不必要的时间复杂性,我们实际上不需要在这里迭代两次。

Array#reduce是我们的工具:

const partition = (predicate, list) => list.reduce(

([left, right], item) => predicate(item) 
? [left.concat(item), right]
: [left, right.concat(item)],

[[], []],
list
);
//===
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const isOdd = n => n % 2;
const [odds, evens] = partition(isOdd, data);
console.log({ odds, evens });

最新更新