symmetricDifference()
只能提供內見的比較方式,若要自行提供 Predicate,就要使用 symmetricDifferenceWith()
。
Version
macOS Mojave 10.14.6
VS Code 1.38.1
Quokka 1.0.253
Ramda 0.26.1
Value
Functional
import { symmetricDifferenceWith } from 'ramda';
let first = [1, 3, 5, 7];
let second = [1, 4, 7];
let fn = symmetricDifferenceWith((x, y) => x === y);
fn(first)(second); // ?
symmetricDifference()
提供的是內定的比較方式,而 symmetricDifferenceWith()
可提供自訂的 predicate。
symmetricDifferenceWith()
((a, a) → Boolean) → [a] → [a] → [a]
回傳不同時存在於兩個 array 的 element,但可提供 predicate 客製化
((a, a) → Boolean)
:決定判斷相等的 predicate
[a]
:第一個 array
[a]
:第二個 array
[a]
:回傳不同時存在於兩個 array 的 element
Point-free
import { symmetricDifferenceWith, equals } from 'ramda';
let first = [1, 3, 5, 7];
let second = [7, 1, 4];
let fn = symmetricDifferenceWith(equals);
console.dir(fn(first)(second));
symmetricDiffernceWith()
的 predicate,也可以使用 equals()
使其 point-free。
Object
Functional
import { symmetricDifferenceWith } from 'ramda';
let first = [
{ firstName: 'Sam', lastName: 'Xiao'},
{ firstName: 'Kevin', lastName: 'Yang'},
{ firstName: 'Jimmy', lastName: 'Huang'},
];
let second = [
{ firstName: 'Kevin', lastName: 'Yang'},
{ firstName: 'Jessie', lastName: 'Hsieh'},
];
let pred = (x, y) => x.firstName === y.firstName && x.lastName === y.lastName;
let fn = symmetricDifferenceWith(pred);
console.dir(fn(first)(second));
symmetricDifference()
也可以搭配 symmetricDifferenceWith()
使用自己的 predicate,此例完全與 symmetricDifference()
相同。
symmetricDifferenceWith()
可貴之處在於自訂 predicate,如只比較lastName
即可,不用比較firstName
,若沒有特別之處,使用symmetricDifference()
即可
Point-free
import { symmetricDifferenceWith, allPass, eqProps } from 'ramda';
let first = [
{ firstName: 'Sam', lastName: 'Xiao'},
{ firstName: 'Kevin', lastName: 'Yang'},
{ firstName: 'Jimmy', lastName: 'Huang'},
];
let second = [
{ firstName: 'Kevin', lastName: 'Yang'},
{ firstName: 'Jessie', lastName: 'Hsieh'},
];
let pred = allPass([
eqProps('firstName'),
eqProps('lastName')
]);
let fn = symmetricDifferenceWith(pred);
console.dir(fn(first)(second));
若 predicate 有多個條件,就很適合使用 allPass()
使其 point-free,且每個條件又可使用 eqProps()
,也是 point-free。
Conclusion
symmetricDifferenceWith()
的 predicate 可由allPass()
與eqProps()
產生,使 predicate 也能 point-free
Reference
Ramda, symmetricDifferenceWith()
Ramda, allPass()
Ramda, eqProps()