使用lodash进行函数式编程会产生意外的输出

时间:2017-05-29 13:21:37

标签: javascript functional-programming ecmascript-6 lodash

我正在努力学习功能编程,我有以下功能:

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()返回的原始对象。

1 个答案:

答案 0 :(得分:0)

我认为问题在于您将调用getAttributestoArraygetTagslowerString的结果作为flow的参数传递功能本身。

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

VS

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

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

VS

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