Trung BìnhJavaScript iconJavaScript

Function composition là gì?

Function composition là tạo hàm mới bằng cách kết hợp nhiều hàm, output của hàm này là input của hàm kia: compose(f, g)(x) = f(g(x)).

Ví dụ: const process = compose(trim, toLowerCase, removeSpaces) tạo pipeline xử lý string. Implement bằng reduce: const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x). pipe là ngược chiều (trái sang phải, dễ đọc hơn). Hữu ích để tạo data transformation pipelines không cần biến trung gian, code theo functional style.

Xem toàn bộ JavaScript cùng filter theo level & chủ đề con.

Mở danh sách JavaScript