只映射一次运行,ramda js

Only run map once, ramda js

const arr = [{
  _id: 'z11231',
  _typename: 'items'
  id: '123',
  comment: null,
  title: 'hello'
}, {
  _id: 'z11231',
  _typename: 'items'
  id: 'qqq',
  comment: 'test',
  title: 'abc'
}]

想要的输出:

[['123', null, 'hello'], ['qqq', 'test', 'abc']];

export const convertObjectsWithValues = R.map(R.values);

export const removeMongoIdAndGraphqlTypeName = R.map(R.omit(['_id', '__typename']));

export const getExcelRows = R.pipe(removeMongoIdAndGraphqlTypeName, convertObjectsWithValues);

这里的问题是我 运行 两张独立的地图。太慢了我能以只执行一张地图的方式组合它吗?并在三个独立的功能中保持清洁?

使用 R.mapR.props 来按您想要的顺序说明您想要的属性。这将始终保持正确的顺序,不像。 R.values,这是通过JS orders keys.

的方式来约束的

const arr = [{"_id":"z11231","_typename":"items","id":"123","comment":null,"title":"hello"},{"_id":"z11231","_typename":"items","id":"qqq","comment":"test","title":"abc"}]

const getExcelRows = keys => R.map(R.props(keys))

const result = getExcelRows(['id', 'comment', 'title'])(arr)

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

我很想知道你是否真的测试过它太慢了。 Knuth 的引述似乎总是 一个建议:"premature optimization is the root of all evil".

但是如果您已经测试过,并且如果多次迭代是您应用程序中的实际瓶颈,那么 composition law of Functors 应该会有所帮助。在 Ramda 术语中,这条定律指出

compose ( map (f), map (g) ) ≍ map (compose (f, g) )

当然还有

pipe ( map (g), map (f) ) ≍ map (pipe (g, f) )

这意味着您可以像这样重写您的函数:

const getExcelRows = map (pipe (omit ( ['_id', '_typename'] ), values ))

const arr = [
  {_id: 'z11231', _typename: 'items', id: '123', comment: null, title: 'hello'},
  {_id: 'z11231', _typename: 'items', id: 'qqq', comment: 'test', title: 'abc'}
]

console .log (
  getExcelRows (arr)
)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script> <script>
const {map, pipe, omit, values} = R                                            </script>