Home > Net >  Is possible to make function from code and make it shorter?
Is possible to make function from code and make it shorter?

Time:12-31

I have this lines of code

let value = productDetails.recentPurchaseDate;
if (!productDetails.salesPrice && !productDetails.recentPurchaseDate) {
  value = false;
}
if (!productDetails.presentEstimatedValue) {
  value = true;
}

Is it possible to refactor, I need to make it function and this two IF? Thanks in advance

CodePudding user response:

You can do it like this

function getValue({
    salesPrice,
    recentPurchaseDate,
    presentEstimatedValue
}) {
    if (!salesPrice && !recentPurchaseDate) return false;
    if (!presentEstimatedValue) return true
    return recentPurchaseDate
}

and then

let value = getValue(productDetails);

CodePudding user response:

Something like that?

const value = yourNewFn();
function yourNewFn() {
    if (!productDetails.salesPrice && !productDetails.recentPurchaseDate) {
    value = false;
  }
  if (!productDetails.presentEstimatedValue) {
    value = true;
  }
  return value;
}

CodePudding user response:

Generally I don't think it is well designed if-conditions, but I don't know your business requirements. Let's try with something like this

let value = productHasRecentPurchaseDate(productDetails); //name should math your bussines goal

function productHasRecentPurchaseDate(productDetails) {
    if (!productDetails.salesPrice && !productDetails.recentPurchaseDate) {
       return false;
    }
    else if (!productDetails.presentEstimatedValue) {
       return true;
    }
    else {
        return /*you need all if statement path to return some value, this is last one, please provide what thos statement should return if both previous conditions fail*/;
    }
}

CodePudding user response:

Then use this

if (!productDetails.salesPrice && !productDetails.recentPurchaseDate && !productDetails.presentEstimatedValue ) : value = false ? value = true;
  • Related