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

184
Visualizações
choose random function according to condition

I have several javascript functions and conditions. Each one of the functions can be excecuted only if the conditions are true. It's possible that two functions will meet the conditions and if this happens, I want to randomly choose a function to execute.

for example:

foo will execute only if cond1 is true goo will execute only if cond2 is true hoo will execute only if cond3 is true

lets say that cond1=true, cond 2=false cond3=true. I want to randomly choose between foo and hoo.

What's the best way to implement that?

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

0

I don't think there's a reason to get fancy here. Just use some ifs to check for your conditions. If a condition applie,s push the corresponding function to an array of possible options. Then select a random value in the array and call it.

const foo = () => console.log("foo");
const goo = () => console.log("goo");
const hoo = () => console.log("hoo");

const cond1 = true;
const cond2 = false;
const cond3 = true;

const options = [];

if (cond1) options.push(foo);
if (cond2) options.push(goo);
if (cond3) options.push(hoo);

options[Math.floor(Math.random() * options.length)]();

And for the friends of shorthand:

const
  foo = () => console.log("foo"),
  goo = () => console.log("goo"),
  hoo = () => console.log("hoo"),
  cond1 = true,
  cond2 = false,
  cond3 = true,
  
  options = [
    ...(cond1 ? [foo] : []),
    ...(cond2 ? [goo] : []),
    ...(cond3 ? [hoo] : []),
  ];
  
  
options[Math.floor(Math.random() * options.length)]();

about 4 years ago · Juan Pablo Isaza Relatório

0

A good data structure for the job would be a list of pairs [condition, function] where condition is also a function. To run a specific func, you filter the list by running conditions first and pick a random item from what's left:

funcs = [
    [
        () => x > 10,
        () => console.log('one'),
    ],
    [
        () => x > 20,
        () => console.log('two'),
    ],
    [
        () => x > 30,
        () => console.log('three'),
    ],
]

let randomItem = a => a[Math.floor(Math.random() * a.length)]

x = 35

// @TODO handle the edge case when no function matches

let pair = randomItem(funcs.filter(p => p[0]()))

pair[1]()

about 4 years ago · Juan Pablo Isaza Relatório

0

"eval" is a good helper for this sutiation;

For example we have 5 function and named by "f1, f2, f3, f4, f5" and conditions are boolean values c1, c2, c3, c4, c5

if randomizing select sum contitions for to test program;

function f1() { console.log("f1 fired!"); }
function f2() { console.log("f2 fired!"); }
function f3() { console.log("f3 fired!"); }
function f4() { console.log("f4 fired!"); }
function f5() { console.log("f5 fired!"); }

var c1 = false;
var c2 = true;
var c3 = false;
var c4 = true;
var c5 = false;


var selectedFunctionNames = [];

function test(){
  if(c1) selectedFunctionNames.push("f1()");
  if(c2) selectedFunctionNames.push("f2()");
  if(c3) selectedFunctionNames.push("f3()");
  if(c4) selectedFunctionNames.push("f4()");
  if(c5) selectedFunctionNames.push("f5()");
  
  if(selectedFunctionNames.length>=1)
    eval(selectedFunctionNames[Math.floor(Math.random() * selectedFunctionNames.length)]);
  else 
    console.log("There is no any function have a condition");
}
<button onclick="test()">Test me</button>
<label>Result in the console</label>

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