Changing the default value of a parameter in a function is possible?

Asked

Viewed 51 times

2

I have an array of functions, and I need to change the default value of the parameter with another value for each of them, in a loop.. Is that possible? Ex:

var externalValidations = [
  function required(v, model = {}) {
     console.log(model)
     return v !== null || 'Campo obrigatório'
  },
  
  function requiredTwo(v, model = {}) {
     console.log(model)
     return v !== null || 'Campo obrigatório'
  },
]

externalValidations.forEach(item => {
  // --> Consigo aqui de alguma forma alterar o valor padrão de um parâmetro para cada função?!.. para ela ficar assim por exemplo: 
  // function requiredTwo(v, model = {valor1: 'valor1'}) {
  //   console.log(model)

  //   return v !== null || 'Campo obrigatório'
  // },
  console.log(item)
})

Thank you!

1 answer

3


It looks like a kind of rolled-up situation, but in the scenario described I would solve by replacing the functions of the array with new ones, which envelop the originals. So:

var externalValidations = [
  function required(v, model = {}) {
     console.log(model)
     return v !== null || 'Campo obrigatório'
  },

  function requiredTwo(v, model = {}) {
     console.log(model)
     return v !== null || 'Campo obrigatório'
  },
];

for (let i=0; i<externalValidations.length; i++) {
    let original = externalValidations[i];
    externalValidations[i] = (v, model = {foo: 'bar'}) => original(v, model);
}
  • Cool Brother, thanks your help I reached a solution here! Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.