Function composition is a powerful technique to build clean, readable code by combining simple functions. Hereโs a practical example:
- Trim whitespace from a username
- Convert the name to uppercase
- Generate a greeting message
- Check out this code snippet:
let username = " Harley ";
const trim = (name) => name.trim();
const convertToUpper = (name) => name.toUpperCase();
const generateMessage = (name) => `Hello ${name}, Good Morning!`;
const result = generateMessage(convertToUpper(trim(username))); // it goes right to left
console.log(result); // "Hello HARLEY, Good Morning!"
By composing these functions, you can transform data step-by-step in a clear and efficient manner. This approach is not only elegant but also helps in maintaining and scaling your code.
Try it out and let me know what you think! ๐๐
Top comments (0)