discard()
若要也能有 discardWith()
,其中一個方法就是借用 withoutWith()
組合而成。
Version
macOS Catalina 10.15.6
Wink-fp 1.23.7
Functional
import { eqProps, of } 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 obj = { title: 'FP in JavaScript', price: 100 }
// discardWith :: ((a, a) -> Boolean) -> a -> [a] -> [a]
let discardWith = pred => v => a => {
let arr = of(v)
return withoutWith(pred, arr, a)
}
discardWith((x, y) => x.title === y.title)(obj)(data) // ?
12 行
// discardWith :: ((a, a) -> Boolean) -> a -> [a] -> [a]
let discardWith = pred => v => a => {
let arr = of(v)
return withoutWith(pred, arr, a)
}
discardWith()
與 withoutWith()
差異只在於一個是傳 value,一個是傳 Array。
- 使用
of()
將 value 轉成 Array - 再使用
withoutWith()
移除 element
Point-free
import { eqProps, of, useWith, identity } 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 obj = { title: 'FP in JavaScript', price: 100 }
// discardWith :: ((a, a) -> Boolean) -> a -> [a] -> [a]
let discardWith = useWith(
withoutWith, [identity, of, identity]
)
discardWith(eqProps('title'), obj, data) // ?
12 行
// discardWith :: ((a, a) -> Boolean) -> a -> [a] -> [a]
let discardWith = useWith(
withoutWith, [identity, of, identity]
)
使用 useWith()
使 discardWith()
能 point-free。
Wink-fp
import { eqProps } from 'ramda'
import { discardWith } from 'wink-fp'
let data = [
{ title: 'FP in JavaScript', price: 100 },
{ title: 'RxJS in Action', price: 200 },
{ title: 'Speaking JavaScript', price: 300 }
]
let obj = { title: 'FP in JavaScript', price: 100 }
discardWith(eqProps('title'), obj, data) // ?
Wink-fp 已經內建 discardWith()
可直接使用。
discardWith()
((a, a) -> Boolean) -> a -> [a] -> [a]
提供自訂條件移除 Array 中 Element
Conclusion
- 帶有
with()
的 function 對於 Object 特別重要,我們可藉此指定只比對 Object 特定 property 比較即可