Ramda JS只运行一次地图

时间:2019-05-24 10:26:27

标签: 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);

问题在这里,我正在运行两个单独的地图。太慢了。我可以仅执行一个映射的方式将其组合吗?并仍然通过三个独立的功能保持干净?

2 个答案:

答案 0 :(得分:1)

我很想知道您是否真的测试过它太慢。克努斯(Knuth)的话总是像个建议:“过早的优化是万恶之源”。

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

$data = $this->db->get_where('table',$number);

当然也是如此

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)
)

答案 1 :(得分:0)

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>