0

Lets say there is one age variable and another variable for the range of the age. I already programmed this script to calculate the dates for search between, but it doesn't always calculate the correct start/end date.

  • If I use as age 30 and range 0, it works correctly (has the person with the age 30).
  • If I use as age 31 and range 1, it works correctly (has the person with the age 30).
  • If I use as age 30 and range 1, it works correctly (has the person with the age 30).
  • If I use as age 30 and range 5, it works correctly (has the person with the age 30).
  • If I use as age 29 and range 1, it doesn't work correctly (hasn't the person with the age 30).

So it seems there is an error with the end date I doesn't find? Here's my script:

if (ageRange && (ageRange < 0 || ageRange > 20)) {
    ageRange = 10;
}
if (age && age >= 18 && age <= 100) {
    var now = new Date();
    var now2 = new Date();

    var startDate = new Date(now.setFullYear(now.getFullYear() - (age - ageRange)));
    startDate.setHours(23);
    startDate.setMinutes(59);
    startDate.setSeconds(59);

    var endDate = new Date(now2.setFullYear(now2.getFullYear() - (age + ageRange)));
    endDate.setHours(0);
    endDate.setMinutes(0);
    endDate.setSeconds(0);

    var findBirthObject = { $lte: startDate, $gte: endDate };
    if (ageRange == 0) {
        startDate = new Date(startDate.valueOf() + 1000);
        startDate.setFullYear(startDate.getFullYear() - 1);

        findBirthObject = { $gte: startDate, $lte: endDate };
    }

}
Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265
David
  • 560
  • 2
  • 10
  • 26

1 Answers1

0

If I use as age 29 and range 1, it doesn't work correctly (hasn't the person with the age 30).

Use modulus arithmetic for this type of range checking. For example:

function ageCheck(age, ageRange)
  {
  if (age % 29 <= ageRange) {
    return "In range"
  }

  else if (age % 29 === 29 - ageRange) {
    return "In range"
  }

  else {
    return "Out of range"
  }
}

ageCheck(27,1)
ageCheck(28,1)
ageCheck(29,1)
ageCheck(30,1)
ageCheck(31,1)
ageCheck(32,1) 
Community
  • 1
  • 1
Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265