在 Ramda 中重写此函数

发布时间:2021-02-25 13:14

我想知道我是否可以使用 Ramda 的函数式风格重写这个函数,但是如何?

有人可以提供一些途径来获得这个吗?

function copyProps(object, props) {
  return props.reduce(
    (acum, current) =>
      object[current] !== undefined && object[current] !== null ? { ...acum, [current]: object[current] } : acum,
    {}
  )
}

用法示例:

user = {
  email: 'mail@example.com'
  another: 'property'
}

const result = copyProps(user, ['email', 'displayName'])

console.log(result) // { email: 'mail@example.com' }
回答1

正如评论中所讨论的,这已经作为 pick 包含在 Ramda 中。

但如果您想推出自己的产品,我们可以通过多种方式实现。

一种是直接翻译您的代码,只需使用一些 Ramda 函数:

const copyProps = (props) => (obj) =>
  reduce ((a, p) => has (p) (obj) ? assoc (p, obj [p], a) : a, {}) (props)

我认为这确实简化了原件,所以它可能很有用。但我更愿意以不同的方式对其进行编码,而不是求助于 ifElsecond 或其他命令式风格的函数。

我们真正想要做的是只包含源对象中存在的那些属性。包含列表的子集是 filter 的重点,所以我宁愿这样写:

const copyProps = (props) => pipe (
  toPairs,
  filter (pipe (head, includes (__, props))),
  fromPairs 
)

const user = {
  email: 'mail@example.com',
  another: 'property',
  whichIs: 'skipped',
  id: 'fred',
}

console .log (
  copyProps (['email', 'displayName', 'id']) (user)
)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js"></script>
<script> const {pipe, toPairs, filter, head, includes, __, fromPairs} = R    </script>