-4

I have to check if input number is smaller or bigger or between two others numbers. I made the correct function but is there any way to write this function more readable and shorter? When at least one of input parameters is not a number the function should return NaN.

function order(num, a, b) {
  if (a > b) {
    return NaN;
  }
  if (num < a) {
    return -1;
  }
  if (num > b) {
    return 1;
  }
  if (a <= num && num <= b) {
    return 0;
  }
  return NaN;
}

// Use case examples
console.log(order(5, 10, 20));
console.log(order(10, 10, 20));
console.log(order(15, 10, 20));
console.log(order(20, 10, 20));
console.log(order(25, 10, 20));

console.log(order(15, 20, 10));
console.log(order(15, 10, undefined));
console.log(order(15, undefined, 20));
console.log(order(15, undefined, undefined));
console.log(order(undefined, 10, 20));
UserTest013
  • 514
  • 6
  • 15

1 Answers1

1

By the looks of it, you have an inherent assumption in the function that a <= b. It is good to have something like an assertion that verifies this condition. See for example What is “assert” in JavaScript?.

That aside, this is an example of a shorter code. Don't think it is any more readable though. At first I thought I reduced the number of if statements, but clearly that's not the case. However, I do think weeding out the non "number" types is important at the beginning rather than the end, and this is more explicit.

function order(num, a, b) {
  if (typeof num != "number" || typeof a != "number" || typeof b != "number")
      return NaN;
  if (num >= a) {
      if (num > b)
          return 1;
      return 0;
  }
  return -1;
}

// Use case examples
console.log(order(5, 10, 20));
console.log(order(10, 10, 20));
console.log(order(15, 10, 20));
console.log(order(20, 10, 20));
console.log(order(25, 10, 20));

console.log(order(15, undefined, 20));
console.log(order(15, undefined, undefined));
console.log(order(undefined, 10, 20));