- vừa được xem lúc

Blog#78: Understanding "Function Composition Pattern" in JavaScript

0 0 14

Người đăng: NGUYỄN ANH TUẤN

Theo Viblo Asia

Để giúp các bạn có thể nâng cao trình độ tiếng Anh, Blog này mình sẽ viết bằng tiếng Anh.

Mục tiêu sẽ là, sử dụng Technical Document để học Tiếng Anh. Mình sẽ cố gắng sử dụng ngữ pháp và từ vựng đơn giản nhất (level~A1/A2) để giúp các bạn đọc nó dễ dàng hơn.


Hi, I'm Tuan, a Full-stack Web Developer from Tokyo 😊. Follow my blog to not miss out on useful and interesting articles in the future.

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.

As always, I hope you enjoyed this article and learned something new. Thank you and see you in the next articles!

If you liked this article, please give me a like and subscribe to support me. Thank you. 😊

Ref

Bình luận

Bài viết tương tự

- vừa được xem lúc

Giới thiệu Typescript - Sự khác nhau giữa Typescript và Javascript

Typescript là gì. TypeScript là một ngôn ngữ giúp cung cấp quy mô lớn hơn so với JavaScript.

0 0 500

- vừa được xem lúc

Bạn đã biết các tips này khi làm việc với chuỗi trong JavaScript chưa ?

Hi xin chào các bạn, tiếp tục chuỗi chủ đề về cái thằng JavaScript này, hôm nay mình sẽ giới thiệu cho các bạn một số thủ thuật hay ho khi làm việc với chuỗi trong JavaScript có thể bạn đã hoặc chưa từng dùng. Cụ thể như nào thì hãy cùng mình tìm hiểu trong bài viết này nhé (go).

0 0 414

- vừa được xem lúc

Một số phương thức với object trong Javascript

Trong Javascript có hỗ trợ các loại dữ liệu cơ bản là giống với hầu hết những ngôn ngữ lập trình khác. Bài viết này mình sẽ giới thiệu về Object và một số phương thức thường dùng với nó.

0 0 136

- vừa được xem lúc

Tìm hiểu về thư viện axios

Giới thiệu. Axios là gì? Axios là một thư viện HTTP Client dựa trên Promise.

0 0 117

- vừa được xem lúc

Imports và Exports trong JavaScript ES6

. Giới thiệu. ES6 cung cấp cho chúng ta import (nhập), export (xuất) các functions, biến từ module này sang module khác và sử dụng nó trong các file khác.

0 0 93

- vừa được xem lúc

Bài toán đọc số thành chữ (phần 2) - Hoàn chỉnh chương trình dưới 100 dòng code

Tiếp tục bài viết còn dang dở ở phần trước Phân tích bài toán đọc số thành chữ (phần 1) - Phân tích đề và những mảnh ghép đầu tiên. Bạn nào chưa đọc thì có thể xem ở link trên trước nhé.

0 0 229