Ramda 之 unionWith()

栏目: JavaScript · 发布时间: 6年前

内容简介:若想將兩個 Array 加以合併,並只保留不重複部分,Ramda 提供了VS Code 1.33.1Quokka 1.0.209

若想將兩個 Array 加以合併,並只保留不重複部分,Ramda 提供了 union() ,但若要自訂比較條件,則要使用 unionWith()

Version

VS Code 1.33.1

Quokka 1.0.209

Ramda 0.26.1

Functional

import { uniqWith, concat } from 'ramda';

let first = [1, 3, 5];
let second = [5, 3, 7];

// unionWith :: ((a, a) → Boolean) → [*] → [*] → [*]
let unionWith = pred => arr1 => arr2 => uniqWith(pred, concat(arr1, arr2));

// fn :: [*] -> [*] -> [*]
let fn = unionWith((x, y) => x === y);

console.log(fn(first)(second));

union() 可透過 concat()uniq() 組合;同理, unionWith() 也可透過 concat()uniqWith() 組合而成。

Ramda 之 unionWith()

unionWith()

import { unionWith } from 'ramda';

let first = [1, 3, 5];
let second = [5, 3, 7];

// fn :: [*] -> [*] -> [*]
let fn = unionWith((x, y) => x === y);

console.log(fn(first)(second));

事實上 Ramda 已經提供 unionWith() ,可直接使用。

unionWith()

((a, a) → Boolean) → [*] → [*] → [*]

自行提供 predicate 決定比較方式,將兩個 array 合併成不重複 array

(a, a) -> Boolean

[*] :第一個 array

[*] :第二個 array

[*] :回傳第一個 array 不存在於第二個 array 部分

Ramda 之 unionWith()

Object

import { unionWith } from 'ramda';

let first = [
  { firstName: 'Sam',   lastName: 'Xiao'},
  { firstName: 'Kevin', lastName: 'Yang'},
  { firstName: 'Jimmy', lastName: 'Huang'},
];

let second = [
  { firstName: 'Kevin', lastName: 'Yang'},
];

// fn :: [*] -> [*] -> [*]
let fn = unionWith((x, y) => x.firstName === y.firstName && x.lastName === y.lastName);

console.dir(fn(first)(second));

unionWith() 也可以用在 object。

由於 unionWith() 是使用 uniqWith() 實現,而 uniqWith() 是使用 equals() 比較,而非 ECMAScript 的 === ,因此比較的是 value equality,而非 reference equality

Ramda 之 unionWith()

Point-free

import { unionWith, allPass, eqProps } from 'ramda';

let first = [
  { firstName: 'Sam',   lastName: 'Xiao'},
  { firstName: 'Kevin', lastName: 'Yang'},
  { firstName: 'Jimmy', lastName: 'Huang'},
];

let second = [
  { firstName: 'Kevin', lastName: 'Yang'},
];

// fn :: [*] -> [*] -> [*]
let fn = unionWith(allPass([
  eqProps('firstName'),
  eqProps('lastName')
]));

console.dir(fn(first)(second));

若 predicate 有多個條件,就很適合使用 allPass() 使其 point-free,且每個條件又可使用 eqProps() ,也是 point-free。

Ramda 之 unionWith()

Conclusion

  • 只要牽涉到比較,Ramda 都是使用自家的 equals() ,而非 ECMAScript 的 === ,因此是 value equality,而非 reference equality

Reference

Ramda , unionWith()

Ramda , concat()

Ramda , uniqWith()

Ramda , allPass()

Ramda , eqProps()


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

嵌入式系统软件设计中的常用算法

嵌入式系统软件设计中的常用算法

周航慈 / 2010-1 / 24.00元

《嵌入式系统软件设计中的常用算法》根据嵌入式系统软件设计需要的常用算法知识编写而成。基本内容有:线性方程组求解、代数插值和曲线拟合、数值积分、能谱处理、数字滤波、数理统计、自动控制、数据排序、数据压缩和检错纠错等常用算法。从嵌入式系统的实际应用出发,用通俗易懂的语言代替枯燥难懂的数学推导,使读者能在比较轻松的条件下学到最基本的常用算法,并为继续学习其他算法打下基础。 《嵌入式系统软件设计中的......一起来看看 《嵌入式系统软件设计中的常用算法》 这本书的介绍吧!

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具