Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

179
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda