Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to preface this by saying the following code is just simple code for easy demonstration. But I am trying to make a currying function (or at least I think thats what its called) in plain js (no react) similar to how react/redux uses dispatch like this:

const action = (val) => (dispatch) => {
  // The function can now use val and dispatch
}

I am passing multiple functions into a associating function that will add a state value and a setState value and I am hoping to be able to use the function like so:

const action = (val) => (state, setState) => {
  // the function can now use val, state, and setState
}

action('foo');

The associating function currently looks like the following:

const action1 = (val) => {
  setState(val);
};

const action2 = (val) => {
  setState(val);
};

const associateActions = (actions) => {
  const associated = {};
  Object.keys(actions).forEach((key) => {
    associated[key] = function (...args) {
      actions[key](...args, state, setState);
    };
  });
  return associated;
};

const associatedActions = associateActions({ action1, action2 });

But I want to be able to pass the state and setState to the actions like so:

const action1 = (val) => (state, setState) => {
  setState(val);
};

const action2 = (val) => (state, setState) => {
  setState(val);
};

I can easily just add the state and setState functions to the end like so (...args, state, setState) but it seems like it can get confusing having them appended to the end like that so I would like to figure out how to write them in a tailing currying function but am unable to figure out how to do so.

Here is a jsFiddle to play with Fiddle Demo

Any help would be appreciated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
160 views
Welcome To Ask or Share your Answers For Others

1 Answer

等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...