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

160
Visualizações
¿Cuál es la mejor manera de manejar los parámetros de funciones dinámicas y opcionales?

Esta es mi función que genera y devuelve una matriz (consulte los comentarios en el código a continuación):

 const getStylesArray = (noteBlockSettings, blockId, key, value) => { // --------------------------------------------------- // noteBlockSettings parameter will be passed to this function no matter what. // So it is definetely not undefined. // NoteBlockSettings has bgOpacity, bgColor, primaryColor, secondaryColor, textColor keys and values. // key and value parameters of this function are optional, so they may be undefined or not. // ***** What i am trying to achieve is : ***** // If key parameter is passed (can be bgOpacity, bgColor, primaryColor, secondaryColor, textColor) // use this passed parameter rather than the value in noteBlockSettings object. // If key parameter is undefined, use the value in noteBlockSettings object. // --------------------------------------------------- let { bgColor, primaryColor, secondaryColor, bgOpacity, textColor } = noteBlockSettings if (key === 'bgColor') { bgColor = value } if (key === 'primaryColor') { primaryColor = value } if (key === 'secondaryColor') { secondaryColor = value } if (key === 'bgOpacity') { bgOpacity = value } if (key === 'textColor') { textColor = value } const stylesArray = [ // Here i am using the variables defined above to dynamically generate the array // Like bgOpacity, bgColor, primaryColor, secondaryColor, textColor etc.. { styleClass: '.head', styleValue: `background:${addAlpha(colord(bgColor).lighten(0.075).toHex(), bgOpacity)}; border-color:${addAlpha(colord(bgColor).darken(0.06).toHex(), bgOpacity)};`, styleTriggers: 'bgColor bgOpacity', }, { styleClass: '.head .options .btn-icon', styleValue: `color:${addAlpha(colord(textColor), 0.4)};`, styleTriggers: 'textColor', }, { styleClass: '.head .options .btn-icon:hover', styleValue: `color:${primaryColor};`, styleTriggers: 'primaryColor', }, . . . ] // Finally returning the generated array return stylesArray }

Esto está funcionando y es solo un intento primitivo. Sin embargo, no sé cómo, pero siento que debería haber una forma mucho más "inteligente" de manejar esto.

Entonces, mi pregunta es: ¿Cuál es la mejor y mínima forma de lograr el mismo resultado?

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

0

Puede crear un objeto de configuración "final" antes de desestructurarlo. Entonces no necesitas verificar cada variable:

 // If `key` is passed and a valid key in the object, copy the object and overwrite // the property. const finalSettings = key in noteBlockSettings ? {...noteBlockSettings, [key]: value} : noteBockSettings; const { bgColor, primaryColor, secondaryColor, bgOpacity, textColor } = finalSettings; // ...

{...noteBlockSettings, [key]: value} básicamente copia noteBlockSettings y establece la propiedad cuyo nombre está en key en value .

Habiendo dicho eso, me pregunto por qué el sitio de llamadas simplemente no pasa el objeto de configuración completo. Eso haría que la API fuera más clara.

about 4 years ago · Juan Pablo Isaza Relatório

0

Simplemente puede obtener una copia de noteBlockSettings y luego extraer cada valor en él.

  1. Copie los valores haciendo
 let copy = {...original};
  1. Modificar cualquier clave:
 copy[key] = value;
  1. Extraiga los valores como lo hizo antes
 let {a, b, c, d, e, ...} = copy 

 const mutateStyles = (noteBlockSettings, blockId, key, value) => { // --------------------------------------------------- // noteBlockSettings parameter will be passed to this function no matter what. // So it is definetely not undefined. // NoteBlockSettings has bgOpacity, bgColor, primaryColor, secondaryColor, textColor keys and values. // key and value parameters of this function are optional, so they may be undefined or not. // ***** What i am trying to achieve is : ***** // If key parameter is passed (can be bgOpacity, bgColor, primaryColor, secondaryColor, textColor) // use this passed parameter rather than the value in noteBlockSettings object. // If key parameter is undefined, use the value in noteBlockSettings object. // --------------------------------------------------- let noteBlockSettingsCopy = {...noteBlockSettings} noteBlockSettingsCopy[key] = value; let { bgColor, primaryColor, secondaryColor, bgOpacity, textColor } = noteBlockSettingsCopy return noteBlockSettingsCopy; } let data = { bgColor: "#fff", primaryColor: '#0ff', secondaryColor: "#ff0", bgOpacity: "0.1", textColor: "#000" }; console.log(mutateStyles(data, 1, "bgColor", "#f0f"));

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