Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

145
Views
Minimice el uso de construcciones if...else para obtener el valor correcto para una propiedad de objeto con algún patrón de diseño si es posible

Quiero asignar un valor a la propiedad al crear un objeto basado en muchas condiciones. Actualmente estoy usando una función separada para obtener el valor de la propiedad, algo como esto:

 function getLocationId(currency, storeCode, isBundle) { if (currency === 'MYR') { if (storeCode === 'store-1') { return 1; } else if (storeCode === 'store-2') { return 2; } } else if (currency === 'SGD') { if (storeCode === 'store-1') { return 3; } else if (storeCode === 'store-2') { // This function can return the same value for a different condition return 2; } else if (!storeCode && !isBundle) { return 8; } } . . . // More conditions, with some involving `isBundle` } function getAccountId(currency, storeCode, paymentMethod) { // Function definition similar to getLocationId // with checks for currency, storeCode, paymentMethod } function getRequestObject(event) { return { . . . location: getLocationId(event.currency, event.storeCode, event.item.isBundle), account: getAccountId(event.currency, event.storeCode, event.paymentMethod), . . . }; }

Siento que hay muchas construcciones if...else usadas con cheques anidados nuevamente. ¿Hacer eso es incluso una buena idea? ¿Hay algún patrón de diseño que pueda usar para crear un objeto de solicitud con el ID de ubicación y el ID de cuenta correctos en función del event de parámetro en getRequestObject ?

PD: no devuelvo el valor entero en el código base real, sino que uso esta biblioteca llamada node-config y almaceno estos ID en un archivo JSON que luego puedo recuperar con config.get('propertyName') .

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Un enfoque un poco más limpio sin sentencias else después de las sentencias return .

 function getLocationId(currency, storeCode, isBundle) { if (currency === 'MYR') { if (storeCode === 'store-1') return 1; if (storeCode === 'store-2') return 2; // other if or return a default value for this currency } if (currency === 'SGD') { if (storeCode === 'store-1') return 3; if (storeCode === 'store-2') return 2; if (!storeCode && !isBundle) return 8; } }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!