DEV Community 👩‍💻👨‍💻

Helder B. Berto
Helder B. Berto

Posted on

🔥 Quick Tip: How to use the Composite design pattern

On this simple trick, I'll show you how to use the Composite design pattern.

const canLowerCase = state => ({
  lower: () => state.text.toLowerCase()
});

const canUpperCase = state => ({
  upper: () => state.text.toUpperCase()
});

const mergeBehaviors = (state, ...behaviors) => 
  Object.assign({}, canLowerCase(state), canUpperCase(state), ...behaviors);

const makeText = text => {
  const state = {
    text,
  };

  const canPrintText = (state) => ({
    print: () => `CURRENT TEXT: "${state.text}"`
  });

  return mergeBehaviors(state, canPrintText(state));
}

const newText = makeText('Lorem Ipsum');

console.log(newText.lower()); // => 'lorem ipsum'
console.log(newText.upper()); // => 'LOREM IPSUM'
console.log(newText.print()); // => 'CURRENT TEXT: "Lorem Ipsum"'
Enter fullscreen mode Exit fullscreen mode

Did you like it? Comment, share! ✨

Top comments (0)

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.