Mastering JavaScript Function Composition: Techniques for Parameter Handling

0

Function composition is a powerful concept in programming. It allows you to combine multiple functions to create more complex functionality. However, composing functions with multiple parameters can be more challenging than it seems. In this article, we’ll explore how to tackle this problem in JavaScript.

Function composition is like pouring maple syrup over pancakes, letting the data flow through. But when dealing with functions that take more than one parameter, this composition might seem impossible. Don’t worry, though. There are methods we can use.

1. Utilize Complex Data Structures

Complex data structures refer to arrays and objects. By returning multiple values in a single array or object, you can simplify the composition process.

For example, let’s consider React’s `useState` hook. This hook returns a value and a setter function as an array:

const [temperature, setTemp] = useState(23);

When combined with transformation functions, you can compose them like this:

const celsiusToFahrenheit = t => t * 9 / 5 + 32;
const fahrenheitToCelsius = t => (t - 32) * 5 / 9;

const stateCelsiusToFahrenheit = ([temperature, setTemp]) => {
   const tempF = celsiusToFahrenheit(temperature);
   const setTempF = tempC => setTemp(fahrenheitToCelsius(tempC));
   return [tempF, setTempF];
};

const useFahrenheit = compose(
    stateCelsiusToFahrenheit,
    useState
);

const [tempF, setTempF] = useFahrenheit(23);

2. Partial Application

Partial application is a technique where you fix some of a function’s parameters to create a new function. For instance, you can partially apply a function that creates HTML elements:

const el = (tag, contents) => `<${tag}>${contents}</${tag}>`;

const ul = el.bind(null, 'ul');
const li = el.bind(null, 'li');

const listify = compose(
    ul,
    list => list.join(''),
    list => list.map(li)
);

const characterList = ['Holmes', 'Watson', 'Mrs. Hudson'];
const characterListHTML = listify(characterList);

3. Currying

Currying is the technique of converting a function with multiple arguments into a sequence of functions each taking a single argument.

const elCurried = tag => contents => `<${tag}>${contents}</${tag}>`;

const map = func => list => list.map(func);
const join = joinStr => list => list.join(joinStr);

const listify = compose(
    elCurried('ul'),
    join(''),
    map(elCurried('li'))
);

const characterList = ['Holmes', 'Watson', 'Mrs. Hudson'];
const characterListHTML = listify(characterList);

Conclusion

In this article, we’ve explored how to handle multiple parameters using techniques like complex data structures, partial application, and currying. By applying these techniques effectively, you can perform even complex tasks efficiently. Maximize the power of function composition with these versatile methods.

References: J.R. Sinclair, “How to Compose Functions that Take Multiple Parameters (Epic Guide)”

Leave a Reply