loading...

πŸ”₯ Quick Tip: How to use the Composite design pattern

helderburato profile image Helder Burato Berto ・1 min read

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"'

Did you like it? Comment, share! ✨

Discussion

markdown guide