Home > Software design >  How to make a condition that evaluates according to a number in Javascript?
How to make a condition that evaluates according to a number in Javascript?

Time:10-11

I want to perform a function that evaluates depending on the amount that is being requested. I will make an example in the context that I need it:

A user had to complete 20 hours of work in the week, if he fulfilled those 20 hours the result will be something like ["start"] but if he did not do it the list will be empty []

But if a user is more than 26 hours old then her list will be something like ["start", "start"]

And if it's past 30 hours then your list will look something like ["start", "start", "start"]

So the variable that I have is hourTracked that symbolizes the hours that the user should meet. I have a condition something like the following:

if (user_week) {
return hourtracked === 20 ? ["start"] : hourtracked >= 28 && hourtracked < 30 ? ["start", "start"] : hourtracked > 30 ? ["start", "start", "start"] : [];
}

but it doesn't seem to be working as it should, maybe the logic is not correct, how should I do it?

CodePudding user response:

Seems you want cut-offs at <20, <26 and <=30

i.e (assuming integer values)

  • 0 to 19 ... result []
  • 20 to 25 ... result ["start"]
  • 26 to 30 ... result ["start", "start"]
  • 31 ... result ["start", "start", "start"]

So

return hourtracked < 20 ? [] : hourtracked < 26 ? ["start"] : hourtracked <= 30 ? ["start", "start"] : ["start", "start", "start"];

To be honest, it's more readable to write it like

if (hourtracked < 20) {
    return [];
}
if (hourtracked < 26) {
    return ["start"];
}
if (hourtracked <= 30) {
    return ["start", "start"];
}
return ["start", "start", "start"];
  • Related