點燈坊

失くすものさえない今が強くなるチャンスよ

使用 withoutWith() 提供 Predicate 對兩個 Array 相減

Sam Xiao's Avatar 2020-09-03

without()difference() 目的相同,都是兩個 Array 相減,唯其 Signature 剛好相反,Ramda 有提供 differenceWith(),但卻沒有 withoutWith(),但我們可以自行組合。

Version

macOS Catalina 10.15.6
Wink-fp 1.23.7

differenceWith()

import { eqProps, differenceWith } from 'ramda'

let data = [
  { title: 'FP in JavaScript', price: 100 },
  { title: 'RxJS in Action', price: 200 },
  { title: 'Speaking JavaScript', price: 300 }
]

let arr = [
  { title: 'FP in JavaScript', price: 100 }
]

// withoutWith :: ((a, a) -> Boolean) -> [a] -> [a] -> [a]
let withoutWith = (pred, a1, a2) => differenceWith(pred, a2, a1)

withoutWith(eqProps('title'), arr, data) // ?

13 行

// withoutWith :: ((a, a) -> Boolean) -> [a] -> [a] -> [a]
let withoutWith = (pred, a1, a2) => differenceWith(pred, a2, a1)

withoutWith() 底層還是 differenceWith(),只是最後兩個 argument 對調。

withoutwith000

Wink-fp

import { eqProps, differenceWith } from 'ramda'
import { withoutWith } from 'wink-fp'

let data = [
  { title: 'FP in JavaScript', price: 100 },
  { title: 'RxJS in Action', price: 200 },
  { title: 'Speaking JavaScript', price: 300 }
]

let arr = [
  { title: 'FP in JavaScript', price: 100 }
]

withoutWith(eqProps('title'), arr, data) // ?

Wink-fp 已經內建 withoutWith() 可直接使用。

withoutWith()
((a, a) -> Boolean) -> [a] -> [a] -> [a]
提供 predicate 對兩個 Array 相減

(a, a) → Boolean:提供自訂 Predicate

[a]:第一個 array

[a]:第二個 array

[a]:回傳相減結果

withoutwith001

Conclusion

  • 帶有 with() 的 function 對於 Object 特別重要,我們可藉此指定只比對 Object 特定 property 比較即可

Reference

Ramda, differenceWith()