Validate difference of 5 points for more or less

Asked

Viewed 100 times

8

I need to make a validation if a value has a difference of up to 5, both for positive and negative. I wonder if there is any Javascript function that helps me in this, without having to do the following if giant:

let scoreboard_local_team = 22;
let scoreboard_visiting_team = 26;
let points = 0;

if (
  scoreboard_local_team + 1 === scoreboard_visiting_team ||
  scoreboard_local_team + 2 === scoreboard_visiting_team ||
  scoreboard_local_team + 3 === scoreboard_visiting_team ||
  scoreboard_local_team + 4 === scoreboard_visiting_team ||
  scoreboard_local_team - 1 === scoreboard_visiting_team ||
  scoreboard_local_team - 2 === scoreboard_visiting_team ||
  scoreboard_local_team - 3 === scoreboard_visiting_team ||
  scoreboard_local_team - 4 === scoreboard_visiting_team
  ) {
  points += 30;
}

console.log(points)

2 answers

9


You can calculate the difference and use Math.abs to obtain the absolute value of this (i.e., the no sign value):

let scoreboard_local_team = 22;
let scoreboard_visiting_team = 26;
let points = 0;
// se a diferença é menor que 5
if (Math.abs(scoreboard_local_team - scoreboard_visiting_team) < 5) {
  points += 30;
}

console.log(points)


It was not very clear whether the difference between the values can be zero, as it does not have this condition in its if. The code above assumes that you can, but if you can’t, just switch to:

let scoreboard_local_team = 22;
let scoreboard_visiting_team = 26;
let points = 0;
let diff = Math.abs(scoreboard_local_team - scoreboard_visiting_team);
if (0 < diff && diff < 5) {
  points += 30;
}

console.log(points)

5

I imagine that there is even an error in this logic and what you want is to establish whether you are within a range, and this is always done by comparing the desired variable with the lowest possible value and the highest possible value. If it’s within the range it’s true, so:

if (scoreboard_visiting_team > scoreboard_local_team - 4 && scoreboard_visiting_team <scoreboard_local_team + 4)

It may be that it really should not be true if it is exactly equal to the value of the variable, so I would need to change a detail and make an exception, but I doubt that this would be correct, the code below makes equal to your code, which I think is wrong:

if (scoreboard_visiting_team > scoreboard_local_team - 4 && scoreboard_visiting_team <scoreboard_local_team + 4 && scoreboard_visiting_team != scoreboard_local_team)

I put in the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.