Bablu Ahmed
Bablu Ahmed

Reputation: 5010

Issue with flow function in lodash

I started to work in a new project where I found lodash's flow function and I saw the uses of it here docs but in my project, in the following code, I found over there flow([...])(state) here what is (state) at the end of the function?

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

Can anyone help me?

Upvotes: 0

Views: 331

Answers (2)

Bablu Ahmed
Bablu Ahmed

Reputation: 5010

So far I found the solution. It actually uses Lodash's curry function.

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"

In the above code, if we notice that for setColumnIndex function has 5 parameters when we are calling from flow function, actually passing 4 parameters and with (state) in curry style total 5 parameters.

Upvotes: 0

LEQADA
LEQADA

Reputation: 1982

According to the lodash documentation, flow returns a function. In JavaScript it is possible to return functions without executing them.

We could refactor the code you provided to the following

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

Upvotes: 1

Related Questions