lodash中的流量函数问题



我开始在一个新项目中工作,在那里我发现了lodash的flow函数,我在这里看到了它的使用文档,但在我的项目中,在下面的代码中,我在那里发现了flow([...])(state),这里是函数末尾的(state)是什么?

module.exports = (async function published(state) {
  return flow([
    setColumnIndex('my_pay_table', 1, 'rate_mode', getColumn('pay_structure', 'pay_per_id', state)),
    setColumnIndex('my_pay_table', 1, 'rate_amount', getColumn('pay_structure', 'pay_rate', state)),
    setColumnIndex('my_wo_title_table', 1, 'user_id', buildArtifact(ownerAlias, 'user', 'id', 1)),
    setColumnIndex('my_wo_title_table', 1, 'date_added', Date.now() / 1000),
  ])(state);
});

有人能帮我吗?

根据lodash文档,flow返回一个函数。在JavaScript中,可以在不执行函数的情况下返回函数。

我们可以重构您提供给以下的代码

module.exports = (async function published(state) {
  // `func` here is a function
  const func = flow([
    setColumnIndex('my_pay_table', 1, 'rate_mode', getColumn('pay_structure', 'pay_per_id', state)),
    setColumnIndex('my_pay_table', 1, 'rate_amount', getColumn('pay_structure', 'pay_rate', state)),
    setColumnIndex('my_wo_title_table', 1, 'user_id', buildArtifact(ownerAlias, 'user', 'id', 1)),
    setColumnIndex('my_wo_title_table', 1, 'date_added', Date.now() / 1000),
  ]);
  // Here we execute that function with an argument `state`
  return func(state);
});

到目前为止,我找到了解决方案。它实际上使用了Lodash的curry函数。

let state = "Initial State";
const setColumnIndex = _.curry((table, index, column, value, state) => {
  if (typeof index !== 'number') {
    throw new Error(`Tried to setColumnIndex and specified a non-numeric index parameter (1): ${index}, did you mean to call setColumn?`);
  }
  return "New state"; // state = "Setting up new state here";
});
let result =_.flow([
    setColumnIndex('my_wo_table', 1, 'status_id', 2),
    setColumnIndex('my_wo_table', 1, 'label_id', 1),
    setColumnIndex('my_wo_table', 1, 'date_added', Date.now() / 1000),
])(state);
console.log(result); //=> "New state"

在上面的代码中,如果我们注意到,当我们从flow函数调用时,setColumnIndex函数有5个参数,实际上传递了4个参数,curry样式中的(state)总共传递了5个参数。

最新更新