Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

145
Visualizações
JS Design Patterns - Factory of methods?

I have a component

export default function PressableText({
   children = "",
   detectionOptions = Object.keys(PATTERNS).map((type) => ({ type })),
   style = commonStyles.text
}) {
   ...
}

PressableText.propTypes = {
   children: PropTypes.string,
   detectionOptions: PropTypes.arrayOf(
      PropTypes.shape({
        type: PropTypes.oneOf(Object.keys(PATTERNS)).isRequired,
        onPress: PropTypes.func,
      })
   ),
   ...
};

As you can see, 'detectionOptions', receives an array of (type, onPress), and the onPress method is optional.

My current PATTERNS object looks like:

export const PATTERNS = {
   username: /@[a-zA-Z0-9_.-]{3,30}/,
   uri: regexForUri,
   phone: regexForPhone,
};

So... basically, what I want to do is to provide a default onPress action for each key.

I have thought to implement a factory, but I am not really good at Design Patterns. Is this considered a factory?

  //
  // CODE INSIDE MY COMPONENT, AS IT ACCESS COMPONENT RELATED STUFF
  //

  const handleOnPressUri = () => { ... };

  const handleOnPressPhone = () => { ... };

  const handleOnPressUsername = () => { ... };

  const defaultPressableActions = useMemo( // IS THIS A FACTORY?
    () => ({
      uri: handleOnPressUri,
      phone: handleOnPressPhone,
      username: handleOnPressUsername,
    }),
    []
  );

  const getPatterns = () =>
    detectionOptions.map(({ type, onPress }) => {
      const pattern = PATTERNS[type];

      if (pattern) {
        return {
          pattern,
          onPress: onPress ?? defaultPressableActions[type],
        };
      }

      throw new Error(`Invalid pattern type.`);
    }
  );

I am asking this, because as far as I know, a factory is a generalized that which returns customized stuff, in a centralized way. But... what about a map that, for each key, returns an action?

Is there any other better solution that comes to your mind in order to refactor this code?

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda