J
J
javanub2018-08-11 21:14:51
JavaScript
javanub, 2018-08-11 21:14:51

Currying, or is it still a function with several parameters?

Currying, or is it still a function with several parameters? What do you usually choose when writing code and why? Explain clearly.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-08-11
@rockon404

Currying is often used in functional programming, when vendor code or some module takes a function as an input parameter and passes its own arguments to it, which you can use, but at the same time want to pass your own:

const foo = myArg => (interfaceArg1, interfaceArg2) => {
  // do something
};

vendor(foo(someValue));

Currying is often used to write middleware. Clearly, static middleware is implemented using currying. Another example using the StyledComponents library (not the easiest, of course):
const buildMediaByConditionFn = conditionFn => (...args) => props => conditionFn(props) && css(...args);
const mobile = buildMediaByConditionFn(props => props.device.isMobile);
const desktop = buildMediaByConditionFn(props => !props.device.isMobile);

const media = {
  mobile,
  desktop,
};

export default media;

The code above will allow us to write, instead of:
const Element = styled.div`
  ${props => props.device.isMobile && css`
    position: fixed;
  `}
`;

So:
const Element = styled.div`
  ${media.mobile`
    position: fixed;
  `}
`;

The construct will be used frequently, while the entire implementation is hidden. Also, the cognitive load from the person accompanying the code is reduced. Therefore, using this approach is very reasonable.
If you are writing simple functions that you want to use later, then write multiple arguments. It doesn't make much sense to rewrite this: Into this:
const square = width => height => height * width;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question