【发布时间】:2019-06-20 12:17:29
【问题描述】:
我有两个对象,一个描述位置的features,另一个描述这些特征的prices。
features = {
improvements: [...] // any array of many id's
building: {} // only one id, may be undefined
}
prices = {
id_1: 10,
...
}
我想遍历features 并整理所有prices。 有时features.building 为undefined,有时features.improvements 为空。
Additional code/workbench on repl.it
我可以用lodash 这样做:
result = _(features.improvements)
.map(feature => prices[feature.id])
.concat(_.cond([
[_.isObject, () => prices[features.building.id]]
])(features.building)) // would like to clean this up
.compact()
.value();
我有兴趣以更实用的方式写这个,我最终得到:
result = _.flow([
_.partialRight(_.map, feature => prices[feature.id]),
_.partialRight(_.concat, _.cond([
[_.isObject, () => prices[features.building.id]]
])(features.building)),
_.compact,
])(features.improvements)
我还是要在中途几乎偷偷打电话给features.building,这让我感觉很尴尬。
我想要的是(伪编码):
flow([
// maybe need some kind of "split([[val, funcs], [val, funcs]])?
// the below doesn't work because the first
// flow's result ends up in the second
// do the improvement getting
flow([
_.map(feature => prices[feature.id])
])(_.get('improvements')),
// do the building getting
flow([
_.cond([
[_.isObject, () => [argument.id]]
])
])(_.get('building')),
// concat and compact the results of both gets
_.concat,
_.compact,
])(features); // just passing the root object in
有可能吗?经验丰富的 FP 程序员会如何处理这个问题?
我对使用 lodash-fp 或 rambda(或任何我可以尝试理解的具有良好文档的内容)编写的解决方案持开放态度,因为这些解决方案可能会提供更简洁的代码,因为它们比标准的 @987654338 更面向功能/咖喱@。
【问题讨论】:
-
您的代码变得复杂并需要
undefined来指示缺少数据的原因是使用了您应该使用unions(产品)的产品类型。 -
我不确定这应该如何适合我的代码。是自定义类型吗?我使用 Vuex 作为数据存储,它更喜欢使用 POJO 和原始类型。
-
难道我还会遇到同样的问题吗?
union({id:_} | not_set),我还需要过滤掉我的not_set值吗?
标签: functional-programming lodash ramda.js