What is the correct syntax for comparing -1, 0, and 1 in JavaScript?

Is there a way to achieve the functionality of a <=> b in JavaScript? It seems that this operator does not exist. Any suggestions for an equivalent function?

Appreciate it, Dorian

Answer №1

Check out this simple demonstration of the functionality of the "spaceship" operator in JavaScript.

const spaceship = (lhs, rhs) =>  lhs < rhs ? -1 : rhs < lhs ? 1 : 0;

To incorporate additional type validation, you can leverage the typeof operator to introduce customized comparison logic.

Kindly Note: The localeCompare method will yield either -1, 0, or 1. Comparators within JavaScript function similarly to the <==> operator and are commonly utilized for array sorting operations.

const spaceship = (lhs, rhs) => {
  const type = typeof lhs;
  if (type !== typeof rhs) { throw new Error('incompatible types') }
  if (type === 'string') { return lhs.localeCompare(rhs); }
  else if (type === 'number') { return Math.sign(lhs - rhs); }
  return lhs < rhs ? -1 : rhs < lhs ? 1 : 0;
}

mocha.setup('bdd')
const { expect } = chai

describe('spaceship operator', () => {
  it('integer comparison', () => {
    expect(spaceship(1, 1)).to.equal( 0); // 1 <=> 1 ===  0
    expect(spaceship(1, 2)).to.equal(-1); // 1 <=> 2 === -1
    expect(spaceship(2, 1)).to.equal( 1); // 2 <=> 1 ===  1
  });
  it('float comparison', () => {
    expect(spaceship(1.5, 1.5)).to.equal( 0); // 1.5 <=> 1.5 ===  0
    expect(spaceship(1.5, 2.5)).to.equal(-1); // 1.5 <=> 2.5 === -1
    expect(spaceship(2.5, 1.5)).to.equal( 1); // 2.5 <=> 1.5 ===  1
  });
  it('string comparison', () => {
    expect(spaceship('a', 'a')).to.equal( 0) // 'a' <=> 'a' ===  0
    expect(spaceship('a', 'b')).to.equal(-1) // 'a' <=> 'b' === -1
    expect(spaceship('b', 'a')).to.equal( 1) // 'b' <=> 'a' ===  1
  });
  it('date comparison', () => {
    const today = new Date(), yestr = new Date(today.getTime() - 8.64e7);
    expect(spaceship(today, today)).to.equal( 0) // 'a' <=> 'a' ===  0
    expect(spaceship(yestr, today)).to.equal(-1) // 'a' <=> 'b' === -1
    expect(spaceship(today, yestr)).to.equal( 1) // 'b' <=> 'a' ===  1
  });
})

mocha.run()
<link href="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.3.4/mocha.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/3.4.1/chai.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.3.4/mocha.js"></script>
<div id="mocha"></div>

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

Exploring the world of jQuery AJAX alongside Google's currency calculator

I'm currently working on a code that utilizes an AJAX call to access the Google currency calculator. The expected outcome is to receive a JSON array that can then be used to gather exchange rate data. Here is the link: http://www.google.com/ig/cal ...

When attempting to delete an item from Firebase using React, the re-render results in the item being

I'm currently in the process of developing an app to enhance my React skills, and I've chosen Firebase for data storage. Everything seems to be working fine as all items from Firebase are rendering properly. However, I've encountered an issu ...

JavaScript's Ajax POST request to PHP is not functioning as expected

My current code setup involves handling $_GET[] requests on the products.php page by passing them to get_data_products.php via an ajax POST request. The data retrieved from get_data_products.php is then displayed accordingly. PHP if(isset($_GET['cat ...

What is the best way to remove all attributes from one interface when comparing to another?

Consider the following two interfaces: interface A { a: number; b: string; } interface B { b: string; } I am interested in creating a new type that includes all the keys from interface A, but excludes any keys that are also present in interface B. ...

Chaining Assignments in TypeScript

let a: { m?: string }; let b = a = {}; b.m = ''; // Property 'm' does not exist on type '{}'. let a: { m?: string } = {}; let b = a; b.m = ''; // It's OK Link to TypeScript Playground What occurs ...

What is the reason behind my difficulty in opening my dialog box modally using JavaScript?

I am looking to keep a dialog open while data is being fetched from the server. Here is the code I have written: (async()=>{ document.getElementById("dialog").showModal(); if(condition1 is true){ await server_call1(); } ...

Position an element with absolute positioning to the right edge of a relative element

I have a situation where I need to align the end of a position absolute element with the end of a relative element, but the relative element's width is not fixed and may vary based on content. https://i.sstatic.net/L2sLP.jpg This scenario arises as ...

The map fails to load on the HTML page

I am struggling to load a map into my HTML page from a file located in the app folder. Despite using the correct code for inserting the map, it still does not load properly. <!-- Contact section start --> <div id="contact" class="contact"> ...

Tips for retaining component data while navigating between components in vue js

If I have two elements, the first one is named X: <template> <input required type='text' v-model.trim="number"> <input type="date" v-model="date" > <button @click='allData(number,date)'>ok</button> <t ...

Ways to access the current element in the Evernote editor that corresponds to the cursor's position?

It seems that Evernote editor uses a Rich Text Editor which differs from the input or textarea tag. Therefore, I am unable to use the provided code to determine its type. Is there a way to retrieve the current element of the Evernote editor where the curso ...

Incorporating SQLSRV results into clickable <td> elements: A dynamic approach

As a newcomer to the world of JS/PHP/web development, I'm seeking help with a seemingly simple task. My goal is to make each <td> element in a table clickable, and retrieve the text contained within the clicked <td>. Currently, I have a S ...

Float and tap

Can someone assist me with my code? I have 4 identical divs like this one, and when I hover over a link, all the elements receive the same code. <div class="Person-team"> <div class="profile-pic-d"> <a cl ...

What is the best way to generate hyperlinks from data in a MongoDB database?

Looking for some assistance in setting up an online discussion forum using node.js, express & mongodb. My current challenge is creating clickable links that will redirect me to the specific page of each article stored in the database. I need to figure out ...

Ensure that the file exists before including it in the $routeProvider template for ng-include

Using Angular routes, I have set up a system where the slug from the URL determines which file to load. The code looks like this: $routeProvider.when("/project/:slug", { controller: "ProjectController", template: function($routeParams){ return & ...

Navigating to an offline HTML webpage using JavaScript in a PhoneGap application

I am currently developing a phonegap application. I am attempting to create a login feature where upon clicking the submit button on the Login.html page, I should be directed to a local HTML file. Login.html <tr> <td>&nbsp;</td> ...

A guide on integrating Pug templating engine with ReactJS

For the integration of Pug with a freshly created ReactJS application, I followed these steps: 1. Started by creating a new ReactJS app using create-react-app 2. Next, I referred to the instructions on babel-plugin-transform-react-pug for installing the ...

Unable to disable webpack HMR

I have set up my project using express version 4.14.0, webpack version 1.14.0 with babel and its presets. I obtained this sample webpack configuration from a reliable source: var path = require('path'); module.exports = { entry: './main. ...

Effortlessly glide to the top of the webpage

After dedicating numerous hours to this task and being a newcomer to JavaScript/JQuery, I am still unsure of how to achieve the following: I have implemented a "back to top" anchor link in the footer of my pages that directs users back to the header. I am ...

Do global variables in a node.js server apply across the entire server or exclusively to individual sessions or users?

I have a question that may seem basic, so I apologize in advance - are global variables in node.js applicable server-wide or is their scope limited to the session or user? For example, if I create a global boolean variable in a routes.js file to track whet ...

how can I insert an asp textbox into a div using jquery?

I have an asp.net textbox (<asp:TextBox></asp:TextBox>), and I would like it so that when I click a button, the textbox is placed inside a div like this output (<div><asp:TextBox></asp:TextBox></div>). I tried using the ...