有没有更好的方法在这里使用applySpec

问题描述 投票:0回答:2

我认为这里的冗余可以通过使用一些函数insde ramda来删除,但我对这个库很新,所以我不能想到如何。一些帮助会非常感激

let lib = {
    getFormattedPropsForUser: R.compose(
        R.pickBy(R.identity),
        R.applySpec({
            username: R.prop('username'),
            password: R.prop('password')
        })),
    getFormattedQueryParamsForUser: R.compose(
        R.pickBy(R.identity),
        R.applySpec({
            _id: R.prop('_id'),
            username: R.prop('username'),
            password: R.prop('password')
        })
    )

};
javascript functional-programming ramda.js
2个回答
1
投票

将两个应用程序的公共部分提取到函数中,并添加使用部分应用程序和object spread向规范添加更多项目的功能。

例:

const forUser = spec => R.compose(
  R.pickBy(R.identity),
  R.applySpec({
    ...spec,
    username: R.prop('username'),
    password: R.prop('password')
  })
)

const lib = {
  getFormattedPropsForUser: forUser(),
  getFormattedQueryParamsForUser: forUser({ _id: R.prop('_id') }),
}

const test = { _id: 'id', username: 'username', password: 'password' }

console.log(lib.getFormattedPropsForUser(test))

console.log(lib.getFormattedQueryParamsForUser(test))
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>

0
投票

我认为你可以相当简化你的功能,并相对容易地抽象出公共部分。这里的getActualProps和你的applySpec / pickBy(identity) shuffle的功能大致相同,实际的字段参数化了。然后可以用它来编写两个函数(或库方法)。

const getActualProps = (names) => pickBy((v, k) => includes(k, names))

const getFormattedPropsForUser = getActualProps(['username', 'password'])
const getFormattedQueryParamsForUser = getActualProps(['_id', 'username'])


// Test
const fred = {_id: 1, name: 'fred', username: 'fflint', password: 'dino'}
const wilma = {_id: 2, name: 'wilma', username: 'wilma42'}
const barney = {_id: 3, name: 'barney', password: 'bam*2'}

console.log(getFormattedPropsForUser(fred))         //~> {password: "dino", username: "fflint"}
console.log(getFormattedQueryParamsForUser(fred))   //~> {_id: 1, username: "fflint"}
console.log(getFormattedPropsForUser(wilma))        //~> {username: "wilma42"}
console.log(getFormattedQueryParamsForUser(wilma))  //~> {_id: 2, username: "wilma42"}
console.log(getFormattedPropsForUser(barney))       //~> {password: "bam*2"}
console.log(getFormattedQueryParamsForUser(barney)) //~> {_id: 3}
<script src="https://bundle.run/[email protected]"></script><script>
const {pickBy, includes} = ramda    </script>
© www.soinside.com 2019 - 2024. All rights reserved.