javascriptsimplifyreadabilitycode-cleanupcode-readability

How to make code more readable and simpler


I have this simple code which i have reduced to as little lines and made as readable as possible. I feel i did a good job but was wandering if it is possible to reduce down further? Any help would be much appreciated, Thanks you

 const hasHourlyRate = hourly_price !== null;
 const hasDayRate = daily_price !== null;
 const hasMonthRate = monthly_price !== null;

 const ratesTypes = !desks
    ? null
    : hasHourlyRate & hasDayRate & hasMonthRate // If all rates are available
    ? [[1, 'Hourly'], [2, 'Day Pass'], [3, 'Monthly Pass']]
    : hasHourlyRate & hasDayRate & !hasMonthRate // If only hourly and daily are available
    ? [[1, 'Hourly'], [2, 'Day Pass']]
    : hasHourlyRate & !hasDayRate & hasMonthRate // If only hourly and monthly are available
    ? [[1, 'Hourly'], [2, 'Monthly Pass']]
    : !hasHourlyRate & hasDayRate & hasMonthRate // If only daily and monthly are available
    ? [[1, 'Day Pass'], [2, 'Monthly Pass']]
    : hasHourlyRate & !hasDayRate & !hasMonthRate // If only hourly is available
    ? [[1, 'Hourly']]
    : !hasHourlyRate & hasDayRate & !hasMonthRate // If only daily is available
    ? [[1, 'Day Pass']]
    : !hasHourlyRate & !hasDayRate & hasMonthRate // If only monthly is available
    ? [[1, 'Monthly Pass']]
    : null;

Solution

  • You could check each condition separately as such.

    arr=[];
    i=1;
    if(hasHourlyRate){
        arr.push([i, "Hourly"]);
        i++;
    }
    if(hasDayRate){
        arr.push([i, "Day Pass"]);
        i++;
    }
    if(hasMonthRate){
        arr.push([i, "Monthly Pass"]);
        i++;
    }
    

    If you can get your values into an array to loop through that would be even better.