|
// Writing a `pick` funciton that "subsets" objects/maps |
|
// using only functional composition and partial-application. |
|
// |
|
// Refer to https://slack-files.com/T06A4UJJH-F0K2AA5A7-44af64e329 for problem details. |
|
// |
|
// Refer to https://slack-files.com/T06A4UJJH-F0K7D0BFZ-5200d77fbe for derivation. |
|
|
|
{ // Pure Ramda.js |
|
const compose = R.compose |
|
const contains = R.contains |
|
const filter = R.pickBy // In rambda, filter is purely by value. |
|
const flip = R.flip |
|
const test = R.pipe(R.equals, console.log) |
|
|
|
let ks = ['a', 'c'] |
|
let m = {a: 11, b: 22, c: 33} |
|
|
|
console.log('Base implementation:') |
|
let pick = compose(filter, compose(flip, flip(contains))) |
|
test(pick(ks)(m), {a: 11, c: 33}) |
|
test(pick(ks, m), {a: 11, c: 33}) // => <function> // Unfortunately, JavaScript can't auto-meld. |
|
|
|
console.log('Manual flattening:') |
|
let pickB = (ks, m) => pick(ks)(m) |
|
//test(pickB(ks)(m), {a: 11, c: 33}) // ! pick2(...) is not a function; NOT OK // Naturally, it's not auto-curried. |
|
console.log(false) // Dummy failure because I can't be bothered to implement tryCatch and Ramda.tryCatch has only been merged last week. |
|
test(pickB(ks, m), {a: 11, c: 33}) // => {"a": 11, "c": 33}; OK |
|
|
|
console.log('Ramda flattening:') |
|
let pickC = R.curryN(2, R.uncurryN(2, pick)) // Ramda uncurry doesn't work as expected. |
|
test(pickC(ks)(m), {a: 11, c: 33}) // => <function> |
|
test(pickC(ks, m), {a: 11, c: 33}) // => <function> |
|
|
|
console.log('Currying a manual flattening:') |
|
let pickD = R.curryN(2, (ks, m) => pick(ks)(m)) // Melding by manual uncurry followed by curry. |
|
test(pickD(ks)(m), {a: 11, c: 33}) |
|
test(pickD(ks, m), {a: 11, c: 33}) |
|
} |
|
|
|
{ // Ramda.js + Sanctuary.js |
|
const contains = R.contains |
|
const filter = R.pickBy |
|
const flip = R.flip |
|
const i = R.identity |
|
const meld = S.meld |
|
const pipe = S.pipe |
|
const test = R.pipe(R.equals, console.log) |
|
|
|
let ks = ['a', 'c'] |
|
let m = {a: 11, b: 22, c: 33} |
|
|
|
const pick = meld([pipe([i, flip(contains), flip]), filter]) |
|
test(pick(ks)(m), {a: 11, c: 33}) |
|
test(pick(ks, m), {a: 11, c: 33}) |
|
} |