+7

Understanding Function Composition Pattern in JavaScript

Function composition is a technique in functional programming where a series of functions are combined into a single function. This can be done by either calling one function inside another or by creating a new function that calls several functions in a specific order. In this article, we will look at how to use the function composition pattern in JavaScript and how it can be useful in functional-oriented programming.

What is the Function Composition Pattern?

The function composition pattern is a way of organizing your code that makes it easy to reuse functions and create new ones by combining existing ones. This pattern involves creating small, specific functions that can be combined in different ways to solve different problems.

Here is an example of the function composition pattern in JavaScript:

const add = x => x + 1;
const multiply = x => x * 2;

const addAndMultiply = x => multiply(add(x));

console.log(addAndMultiply(2)); // 6

In this example, we have two functions, add and multiply. The addAndMultiply function is the composition of these two functions. When we call addAndMultiply with an argument of 2, it calls add with an argument of 2 and then passes the result (3) to multiply, which returns 6.

Why Use the Function Composition Pattern?

There are several reasons why you might want to use the function composition pattern in your code:

  • Reusable code: The function composition pattern allows you to reuse code by breaking it down into smaller, more specific functions. These smaller functions can be combined in different ways to solve different problems.

  • Easier to read: The function composition pattern can make your code easier to read by breaking it down into smaller, more specific functions. This can make it easier to understand what each function does and how they fit together.

  • Easier to test: When you use the function composition pattern, you can test each individual function separately. This can make it easier to identify any issues and fix them.

Example 1: Converting Celsius to Fahrenheit

In this example, we will use the function composition pattern to convert a temperature from Celsius to Fahrenheit.

const celsiusToFahrenheit = celsius => celsius * 9 / 5 + 32;

console.log(celsiusToFahrenheit(0)); // 32
console.log(celsiusToFahrenheit(100)); // 212

In this example, we have a single function called celsiusToFahrenheit which converts a temperature from Celsius to Fahrenheit. When we call this function with an argument, it performs the necessary calculation and returns the temperature in Fahrenheit.

Example 2: Validating Form Data

In this example, we will use the function composition pattern to validate form data.

const isNotEmpty = value => value !== "";
const isValidEmail = email => email.includes("@");

const validateForm = data => {
  const errors = {};
  if (isNotEmpty(data.name)) {
    errors.name = "Name is required";
  }
  if (!isValidEmail(data.email)) {
    errors.email = "Email is invalid";
  }
  return errors;
};

console.log(validateForm({ name: "", email: "example@email.com" }));
// { name: "Name is required" }
console.log(validateForm({ name: "John", email: "invalid" }));
// { email: "Email is invalid" }

In this example, we have two functions, isNotEmpty and isValidEmail, which check if a value is not empty and if an email is valid, respectively. The validateForm function is the composition of these two functions. It takes an object of form data as an argument and returns an object of errors.

Example 3: Creating a URL

In this example, we will use function composition to create a URL from a base URL and an object of query parameters.

const addQueryParams = (url, params) => {
  const queryString = Object.keys(params)
    .map(key => `${key}=${params[key]}`)
    .join("&");
  return `${url}?${queryString}`;
};

const createUrl = (baseUrl, params) => addQueryParams(baseUrl, params);

console.log(createUrl("https://example.com", { page: 2, filter: "popular" }));
// "https://example.com?page=2&filter=popular"

In this example, we have two functions, addQueryParams and createUrl. The createUrl function is the composition of these two functions. It takes a base URL and an object of query parameters as arguments and returns a full URL with the query parameters appended to it.

Example 4: Calculating Sales Tax

In this example, we will use function composition to calculate the sales tax on a purchase.

const getBasePrice = item => item.price;
const getTaxRate = item => item.taxRate;
const getTax = (basePrice, taxRate) => basePrice * taxRate;
const addTax = (basePrice, tax) => basePrice + tax;

const calculateTotal = item => addTax(getBasePrice(item), getTax(getBasePrice(item), getTaxRate(item)));

console.log(calculateTotal({ price: 10, taxRate: 0.1 })); // 11

In this example, we have four functions: getBasePrice, getTaxRate, getTax, and addTax. The calculateTotal function is the composition of these four functions. It takes an object representing an item and returns the total price of the item, including tax.

Example 5: Filtering and Sorting Data

In this example, we will use function composition to filter and sort a list of objects.

const filterByType = (type, items) => items.filter(item => item.type === type);
const sortByName = items => items.sort((a, b) => a.name.localeCompare(b.name));

const getSortedType = (type, items) => sortByName(filterByType(type, items));

const data = [
{ name: "Alice", type: "fruit" },
{ name: "Bob", type: "vegetable" },
{ name: "Eve", type: "fruit" }
];

console.log(getSortedType("fruit", data));
// [ { name: "Alice", type: "fruit" }, { name: "Eve", type: "fruit" } ]

In this example, we have two functions, filterByType and sortByName, which filter a list of items by type and sort them by name, respectively. The getSortedType function is the composition of these two functions. It takes a type and a list of items as arguments and returns a new list of items that are filtered by the given type and sorted by name.

Conclusion

The function composition pattern is a useful way to organize your code and make it easier to reuse and combine functions. By breaking your code down into smaller, more specific functions, you can create more modular, flexible, and maintainable code. The function composition pattern can also make your code easier to read and test.

Mình hy vọng bạn thích bài viết này và học thêm được điều gì đó mới.

Donate mình một ly cafe hoặc 1 cây bút bi để mình có thêm động lực cho ra nhiều bài viết hay và chất lượng hơn trong tương lai nhé. À mà nếu bạn có bất kỳ câu hỏi nào thì đừng ngại comment hoặc liên hệ mình qua: Zalo - 0374226770 hoặc Facebook. Mình xin cảm ơn.

Momo: NGUYỄN ANH TUẤN - 0374226770

TPBank: NGUYỄN ANH TUẤN - 0374226770 (hoặc 01681423001)

image.png


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí