Is there a way to determine whether a number is lesser, greater, or falls within a specific range of values

Is there a more concise and readable way to write a function that checks if a given number is smaller, larger, or between two other numbers? The function should return NaN if any of the input parameters are not numbers.

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));

Answer №1

Upon inspection, it appears that there is an underlying assumption in the function that a <= b. It would be beneficial to include an assertion to confirm this condition. Take a look at What is “assert” in JavaScript? for reference.

Putting that aside, this serves as a concise code example. Although it may not necessarily be more readable. Initially, it seemed as though the number of if statements had been reduced, but upon closer examination, that is not the case. Nonetheless, filtering out non-numeric types at the beginning rather than the end is crucial, and this approach 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;
}

// Usage 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));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Locate the parent element using a unique child element, then interact with a different child element

Can you help me come up with the correct xpath selector for this specific element? The element only has a unique href. Is it possible to locate the element by searching for the text iphone X within the href="#">iphone X and also checking for its paren ...

Retrieving data from Ajax and passing it to PHP

I am currently facing an issue with my Ajax code. When I try to access a textfield variable in PHP after alerting the value successfully, I receive an error stating Undefined index. Javascript Code <SCRIPT> function sendData(UserID) { var name = en ...

Unable to reset iframe style height in IE8 using JavaScript

I am encountering an issue with resetting the height of an iframe using JavaScript. Here is the code snippet I am working with: var urlpxExt = document.getElementById('urlPx'); urlpxExt.style.height = "200px"; While this approach works well in m ...

I'm looking to integrate Jest in my React project with npm. How can I achieve

I've developed my application with create react app and npm. While reviewing the official documentation for jest at https://jestjs.io/docs/tutorial-react, I noticed that they only provide information on testing CRA apps using yarn. Does this suggest t ...

Centering the scrollIntoView feature on mobile devices is presenting challenges with NextJS applications

Description While navigating on mobile browsers, I'm facing a challenge with keeping an element centered as I scroll due to the browser window minimizing. I've experimented with different solutions such as utilizing the react-scroll library and ...

How can we dynamically resize page content to fit varying browser window sizes across different devices with the help of jQuery/JavaScript?

Looking for a solution involving an HTML form that includes a text field and a submit button. The text field is where the user enters a URL, and upon clicking the submit button, they are redirected to that URL. Seeking a way to adjust the size of the new ...

The distortion of Blender animation becomes apparent once it is imported into three.js

I've been working on a project where I'm incorporating animations into a scene using a combination of blender and three.js. It took me several hours of trial and error to finally get the model and animation successfully imported into three.js. I ...

Using Angular to populate textboxes with SQL data

I am encountering an issue with a mat-table that retrieves its data from a database. One of the columns needs to be editable by the user so that they can update the content and reflect changes in the database. The problem lies in loading the data into the ...

The search function in Typeahead is not activating the API request while typing

Having some trouble implementing a typeahead search feature in my nodejs application with mysql. I can't seem to figure out what's wrong with my code. When I manually access http://localhost:5000/search?key=s, I'm able to see the results an ...

Correctly align the div on the screen as the viewport is scrolled

I am currently working on a parallax website where the sliders are designed to slide from the left and align within the viewport as the user scrolls. However, I have encountered an issue where multiple scroll actions are required for the slide to align pro ...

JavaScript allows users to input an array name themselves

When fetching rows from my database using AJAX, I transform them into an array with a variable identifier. Here is the PHP code: $query_val = $_GET["val"]; $result = mysql_query("SELECT * FROM eventos_main WHERE nome_evento LIKE '%$query_val%&apos ...

Transferring event arguments to JavaScript in ASP.NET C# through OnClientClick

Currently, I have an asp button on my webpage. In the code behind within the Page_Load method, I am assigning some JavaScript calls in the following manner. btnExample.OnClientClicking = "functionOne(1,2);"+"function2()"; However, I am encountering a pro ...

Adjustable annotations in flot chart

When creating a flot, I can draw segments by specifying the markings in the options. markings: [ { xaxis: { from: 150, to: 200 }, color: "#ff8888" }, { xaxis: { from: 500, to: 750 }, color: "#ff8888" } ] Now, I am looking to remove these existing m ...

Ajax encountered a problem while attempting to download the file

I have a situation where JavaScript generates content within a function, and I need to save that content in my downloads folder. However, when I attempt to do so via AJAX, it does not work and no errors are being displayed. Here is the JS code: $.ajax({ ...

JavaScript layout: Thymealf

I have a unique thymeleaf template like so: <body> <div id="layout"> <!-- Menu toggle --> <a href="#menu" id="menuLink" class="menu-link"> <!-- Hamburger icon --> <span>& ...

Manipulate an object in Three.js using the ObjLoader functionality

I'm currently working on manipulating an object loaded using OBJLoader in Three.js. The issue I'm facing is that while it's easy to manipulate the object once, I can't figure out how to do so during the animate loop or anywhere outside ...

What is preventing me from utilizing middleware in my express route?

I have a project in progress where I am developing an API. As part of this process, I need to implement a user system and ensure secure access to the API. Below is the middleware function used for validation: 'use strict' const jwt = require(& ...

Establish and define the global variable "Protractor"

In order to pass a string value from the function editPage.CreateEntity();, you can use that value in multiple test cases by assigning it to the variable entityName. You are able to retrieve the value by setting up the test case as follows: fit('Te ...

How can I replay an HTML audio element?

I created an HTML5 page with an audio element for playing music in mp3 format. However, when the music plays to the end, it stops and I'm using JavaScript to control the audio element. Even so, I can't seem to replay it, only stop it. Is there a ...

No results appearing in the output section

While developing a website using React, I encountered an error that said useState is defined but never used in the navbar component. To address this, I made changes to my ESLint configuration in the package.json file: "rules": { "eqeqe ...