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

105
Visualizações
Make values inside javascript array conditional

How do I make the named array values conditional?

Here in the below code, I have the params array to which I am adding one more named parameter in the if conditions. In the if condition that says INSERT I want to have the userId and the displayName field and in the condition that says REMOVE I only want the userId field.

The whole point is to make the code look cleaner by not repeating the same code twice but have it at one place and make the displayName conditional depending on it is INSERT or REMOVE condition. My actual code has lot more conditions and looks really long repeating it in each of those if conditions.

 var params = {
        secretArn: 'secretArn',
        resourceArn: 'resourceArn',
        database: 'db',
    };

if (record.eventName == 'INSERT') {
        params.parameters = [{
                  name: "userId",
                        value: {
                            "stringValue": userId
                        }
                    },
                    {
                        name: "displayName",
                        value: {
                            "stringValue": displayName
                        }
                    },
                ];

       }
if (record.eventName == 'REMOVE') {
        params.parameters = [{
                  name: "userId",
                        value: {
                            "stringValue": userId
                        }
                    },
                    {
                        name: "displayName",
                        value: {
                            "stringValue": displayName
                        }
                    },
                ];

       }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

After thinking about Q, it seems that the core solution should be an implementation of the dynamic dispatch pattern (I could be incorrect in the name of the pattern). Here is a sample solution:

const getUserId = () => Math.ceil(Math.random() * 100);

const getDisplayName = () => {
  const names = ['Sebastian', 'Farrell', 'Artur', 'Geghard', 'Matevos'];
  return names[Math.floor(Math.random() * names.length)];
};

const makeParametr = (name, stringValue) => () => ({
    name,
    value: { stringValue },
});

const dispatcher = {
  INSERT: [
    { func: makeParametr, args: [() => 'userId', getUserId] },
    { func: makeParametr, args: [() => 'displayName', getDisplayName] },
  ],
  REMOVE: [
    { func: makeParametr, args: [() => 'userId', getUserId] },
  ],
};

const getParameters = (eventName) => {
  if (!dispatcher[eventName]) throw new Error(`No such event: ${eventName}`);

  return dispatcher[eventName].map(({ func, args }) => {
    const currentArgs = args.map((arg) => arg());

    return func(...currentArgs)();
  }) 
};

console.log(getParameters('INSERT'));
console.log(getParameters('REMOVE'));
console.log(getParameters('OTHER_EVENT'));
.as-console-wrapper{min-height: 100%!important; top: 0}

about 4 years ago · Juan Pablo Isaza Relatório
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