【问题标题】:Functional programming with lodash yields unexpected output使用 lodash 进行函数式编程会产生意外的输出
【发布时间】:2017-05-29 13:21:37
【问题描述】:

我正在研究函数式编程,我有以下功能:

fp = lodash/fp, _ = lodash (not yet optimized)

// Reference functions 
const getAttributes = fp.getOr({}, `attributes`)
const toArray = fp.curry(input => _.isArray(input) ? [...input] : input ? [input] : [] )

const getTags = fp.flow(getAttributes(), fp.getOr([], 'tags'), toArray())
// returns ['tag 1', 'Tag 2', ...] or else an empty array.


const lowerString = fp.map( taxonomy => taxonomy ? taxonomy.toLowerCase() : '' )
// Used to normalize the tags to lowercase.


const normalizeTags = fp.flow(getTags(), (d) => {console.log(d); return d}, lowerString())
// My composed function that combines the two

问题是console.log() 之间的结果以及我的lowerString() 错误的原因是getAttributes() 返回的原始对象。

【问题讨论】:

  • 你能在 Plunker 或类似的东西上为我们设置一个工作示例吗?

标签: javascript functional-programming ecmascript-6 lodash


【解决方案1】:

我认为问题在于您将调用getAttributestoArraygetTagslowerString 的结果作为参数传递给flow,而不是函数本身。

const getTags = fp.flow(getAttributes(), fp.getOr([], 'tags'), toArray())

const getTags = fp.flow(getAttributes, fp.getOr([], 'tags'), toArray)

const normalizeTags = fp.flow(getTags(), (d) => {console.log(d); return d}, lowerString())

const normalizeTags = fp.flow(getTags, (d) => {console.log(d); return d}, lowerString)

【讨论】:

  • 谢谢!我错过了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-07
  • 1970-01-01
  • 1970-01-01
  • 2020-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多