Как вернуть логическое значение на основе значения объекта? - PullRequest
0 голосов
/ 22 мая 2019

Попытка вернуть логическое значение, если объект rejectMessage содержит код, который я указал в методе checkErrorCodes. он должен возвращать значение true, еслилокация сопоставления соответствует своему не возвращаемому логическому значению, он переустанавливает всю функцию isError. Любая идея или лучший подход, чтобы сделать это?

transformPrice.js

function transformPrice(oldDrugPrice) {
      let drugPrice =  {
            "drugName": "Metformin",
            "mailPrice": {
                "copayEmployer": "N/A",
                "totalQuantity": "90.0",
                "rejectMessage": [{
                    "settlementCode": "99",
                    "settlementDesc": "Not Covered: Call us - System could not process your request. Call us at the toll-free number on your benefit ID card.||Sin cobertura: Llámenos - El sistema no pudo procesar su solicitud. Llame al número gratuito que figura en su tarjeta de identificación de beneficios."
                }]
            },
            "retailPrice": {
                "copayEmployer": "N/A",
                "totalQuantity": "30.0"
            }
        },

      if (drugPrice.retailPrice.rejectMessage || drugPrice.mailPrice.rejectMessage.length ){
        const retailRejecrMsg = drugPrice.retailPrice.rejectMessage;
        const mailPriceMsg = drugPrice.mailPrice.rejectMessage;
         const retailErr = isErrorPresent(retailRejecrMsg);
         const mailErr =isErrorPresent(mailPriceMsg);

      }

      return drugPrice;
    }

Метод isErrorPresent

function isErrorPresent (price) {
  const isError = function (element) {
    const bRet = checkErrorCodes(element);
    return (element.hasOwnProperty('settlementCode') && bRet)
  }

  return isError;
}

метод checkErrorCodes

function checkErrorCodes(el){
  let bRet = false;
  const errorCodes = [
    10015,
    2356,
    225,
    224,
      99
  ]

  for (const err of errorCodes){

    if (err === el.settlementCode){

      bRet = true;
    }
  }
   return bRet;
}

Ответы [ 5 ]

0 голосов
/ 23 мая 2019

Я запустил ваш код и обнаружил несколько проблем:

  • Метод isErrorPresent возвращает метод isError, а не значение
  • в методе transformPrice у вас есть некоторые проблемы, такие как:
    • отсутствует точка с запятой перед Если оператор
    • rejectMessage является массивом, к которому вы должны обращаться через индекс.
    • вы не проверяли ноль для retailRejecrMsg и mailPriceMsg

Также я не знаю, что вы хотите после проверки Ошибка, поэтому я добавляю значение в drugPrice.mailErr и drugPrice.retailErr.

Я исправил, надеюсь, это поможет.

function transformPrice() {
      let drugPrice =  {
            "drugName": "Metformin",
            "mailPrice": {
                "copayEmployer": "N/A",
                "totalQuantity": "90.0",
                "rejectMessage": [{
                    "settlementCode": "99",
                    "settlementDesc": "Not Covered: Call us - System could not process your request. Call us at the toll-free number on your benefit ID card.||Sin cobertura: Llámenos - El sistema no pudo procesar su solicitud. Llame al número gratuito que figura en su tarjeta de identificación de beneficios."
                }]
            },
            "retailPrice": {
                "copayEmployer": "N/A",
                "totalQuantity": "30.0"
            }
        };

      if (drugPrice.retailPrice.rejectMessage || drugPrice.mailPrice.rejectMessage.length ){
        const retailRejecrMsg = drugPrice.retailPrice.rejectMessage ? drugPrice.retailPrice.rejectMessage[0]: null;
        const mailPriceMsg = drugPrice.mailPrice.rejectMessage ? drugPrice.mailPrice.rejectMessage[0]: null;
        drugPrice.retailErr = !retailRejecrMsg ? true : isErrorPresent(retailRejecrMsg);
        drugPrice.mailErr = !mailPriceMsg ? true : isErrorPresent(mailPriceMsg);
      }

      return drugPrice;
}

function isErrorPresent (price) {
    const bRet = checkErrorCodes(price);
    return (price.hasOwnProperty('settlementCode') && bRet)
}

function checkErrorCodes(el){
  let bRet = false;
  const errorCodes = [
    10015,
    2356,
    225,
    224,
    99
  ]

  for (const err of errorCodes){
    if (err === el.settlementCode){
      bRet = true;
    }
  }
   return bRet;
}
console.log(transformPrice())
0 голосов
/ 22 мая 2019

Вы можете использовать что-то вроде этого:

function isErrorPresent (obj) {

  if(checkErrorCodes(obj) && obj.hasOwnProperty('settlementCode')){ //error code checked
    return obj; //return obj
  }
  return false; //no error found

}

function checkErrorCodes(el){
  const errorCodes = [
    10015,
    2356,
    225,
    224,
      99
  ]
  return errorCodes.includes(el.settlementCode);
}

Вот как я бы подошел к этому.Надеюсь, это поможет.

0 голосов
/ 22 мая 2019

В функции isErrorPresent вы никогда не вызываете функцию isError.Чтобы вызвать его, вы должны:

return isError(price)

, это вызовет функцию с аргументом price, поэтому в вашем примере это будет выглядеть так:

function isErrorPresent (price) {
  const isError = function (element) {
    const bRet = checkErrorCodes(element);
    return (element.hasOwnProperty('settlementCode') && bRet)
  }

  return isError(price);
}
0 голосов
/ 22 мая 2019
Здесь вы создаете функцию, которая возвращает другую функцию:
function isErrorPresent (price) {
  const isError = function (element) {
    const bRet = checkErrorCodes(element);
    return (element.hasOwnProperty('settlementCode') && bRet)
  }

  return isError;
}

Если вы посмотрите внимательно, вы увидите, что return isError на самом деле возвращает ссылку на функцию, а не результат функции после нее.был вызван.

Вы можете вызвать две функции следующим образом: isErrorPresent(price)(element)


или определить функцию следующим образом:

function isErrorPresent (price, element) {
    const bRet = checkErrorCodes(element);
    return (element.hasOwnProperty('settlementCode') && bRet);
}

и затем вызватьэто как isErrorPresent(price, element).

0 голосов
/ 22 мая 2019

как насчет вызова метода is

const mailErr =isErrorPresent(mailPriceMsg).call();

или изменения метода isErrorPresent

function isErrorPresent (price, element) {
    const bRet = checkErrorCodes(element);
    return (element.hasOwnProperty('settlementCode') && bRet)
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...