Michael
Michael

Reputation: 443

Clean way to set numerical value by comparison conditional

I have the following const "maxRange" ... that compares two values and then sets to one of those values if less than. Is there a better/cleaner way to achieve this same logic?

const maxRange = Math.round(averageTotalPrice / 50) * 50 * 5.5 < maxTotalPrice ? Math.round(averageTotalPrice / 50) * 50 * 5.5 : maxTotalPrice

Upvotes: 0

Views: 32

Answers (3)

Nathan
Nathan

Reputation: 4067

I would start by getting rid of the magical numbers 50 and 5.5 and using Math.min instead of the ternary operator.

If Math.round(averageTotalPrice / MAGICAL_50) * MAGICAL_50 * MAGICAL_5_5 is not absolutely obvious in the domain you are working on, I would also put that in a constant just to make clear what that is all about.

Here is a hypothetical:

const BUCKET_SIZE = 5.5;
const WHOLESALE_AMOUNT = 50;
const maxRange = Math.min(Math.round(averageTotalPrice / WHOLESALE_AMOUNT ) * WHOLESALE_AMOUNT * BUCKET_SIZE, maxTotalPrice);

Upvotes: 0

ali memar
ali memar

Reputation: 270

I think this better

let round = Math.round(averageTotalPrice / 50) * 50 * 5.5;
const maxRange = Math.min(round, maxTotalPrice);

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370809

Looks like you need Math.min:

const maxRange = Math.min(
    Math.round(averageTotalPrice / 50) * 50 * 5.5,
    maxTotalPrice
);

Upvotes: 1

Related Questions