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

130
Vistas
Optimize javascript function code if ... else

I implemented a logic that forces me to create many conditions based on different properties value. At first i thought i could refactor it with switch ... case statements but as it does not depend on a single value, i can't go for this solution.

If it were you, how would be optimize, maintain this code ? context: We are in a React Component, so maybe i could also use useCallback or UseMemo ?

function navigateToNextStep() {
    if (
      user.lifecycle.stepCompany === 'todo' ||
      user.lifecycle.stepCompany === 'progress'
    ) {
      navigation.navigate(App.SETUP.COMPANY);
    }
    if (
      user.lifecycle.stepIdentity === 'todo' ||
      user.lifecycle.stepIdentity === 'progress'
    ) {
      navigation.navigate(App.SETUP.IDENTITY);
    }
    if (user.lifecycle.stepFinalize === 'todo') {
      navigation.navigate(App.SETUP.FINALIZE);
    }
    if (user.lifecycle.stepIdentity === 'awaiting_review') {
      navigation.navigate(App.SETUP.MODAL.AWAITING_REVIEW);
    }
    if (user.lifecycle.stepIdentity === 'need_approval') {
      navigation.navigate(App.SETUP.MODAL.APPROVAL_REQUIRED);
    }
  } 
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

If you have quite complicated if-else statements take a look at RulesEngine,

This is a set of production rules, each of which has a condition and an action - simplistically you can think of it as a bunch of if-then statements.

maybe in your case, it's the best way to simplify(but in most cases, if-else or switch-case enough).

Here you can find different implementations for js. Take a look at json-rules-engine as an example:

This example demonstates an engine for identifying employees who work for Microsoft and are taking Christmas day off.

const { Engine } = require('json-rules-engine')


/**
 * Setup a new engine
 */
let engine = new Engine()

// define a rule for detecting the player has exceeded foul limits.  Foul out any player who:
// (has committed 5 fouls AND game is 40 minutes) OR (has committed 6 fouls AND game is 48 minutes)
engine.addRule({
  conditions: {
    any: [{
      all: [{
        fact: 'gameDuration',
        operator: 'equal',
        value: 40
      }, {
        fact: 'personalFoulCount',
        operator: 'greaterThanInclusive',
        value: 5
      }]
    }, {
      all: [{
        fact: 'gameDuration',
        operator: 'equal',
        value: 48
      }, {
        fact: 'personalFoulCount',
        operator: 'greaterThanInclusive',
        value: 6
      }]
    }]
  },
  event: {  // define the event to fire when the conditions evaluate truthy
    type: 'fouledOut',
    params: {
      message: 'Player has fouled out!'
    }
  }
})

/**
 * Define facts the engine will use to evaluate the conditions above.
 * Facts may also be loaded asynchronously at runtime; see the advanced example below
 */
let facts = {
  personalFoulCount: 6,
  gameDuration: 40
}

// Run the engine to evaluate
engine
  .run(facts)
  .then(({ events }) => {
    events.map(event => console.log(event.params.message))
  })

/*
 * Output:
 *
 * Player has fouled out!
 */

Or you can write a simple implementation of Rule Engine based on Object on your own.

As an example for your case:

const rules = [{
    rule: (user) => ['todo', 'progress'].includes(user.lifecycle.stepCompany),
    action: () => console.log("App.SETUP.COMPANY")
  },
  {
    rule: (user) => ['todo', 'progress'].includes(user.lifecycle.stepIdentity),
    action: () => console.log("App.SETUP.IDENTITY")
  }
]

const user = {
  lifecycle: {
    stepCompany: 'todo',
    stepIdentity: 'progress'
  }
}

rules.forEach(r => {
  if (r.rule(user)) {
    r.action()
  }
})

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