Compare Objects In JavaScript With Tiny Evaluable Library

Category: Javascript | January 4, 2024
AuthorMaxRoecker
Last UpdateJanuary 4, 2024
LicenseMIT
Tags
Views30 views
Compare Objects In JavaScript With Tiny Evaluable Library

Evaluable is a tiny yet robust JavaScript library that offers a unique approach to determining the equality of various data types. Similar to the same-value-zero algorithm used in collections like Set and Map, but it also considers custom equals and valueOf methods.

This library differs from built-in JavaScript comparison operators like == and ===, as well as libraries like Immutable.js and Object.is. It aims to provide value equality with sensible handling of edge cases.

How to use it:

1. Install and import the evaluable module.

# NPM
$ npm i evaluable
import { is } from 'evaluable';

2. The is() function in Evaluable accepts two values to compare, a and b. An optional delta parameter can be passed to compare numbers approximately.

// true
is(null, null);
// false
is(null, undefined);
// false
is(null, ''); // returns false
// true
is(+0, -0);
// true
is(0.1 + 0.2, 0.3);
// true
is(NaN, NaN);
// true
is('abc', 'abc');
// true
is('\u00F1', '\u006E\u0303');
// true
is(new Date(0), new Date(0));
// true
is(new Number(1), new Number(1));

3. You can also create custom classes with the equals method.

class Custom {
  constructor(value) {
    this.value = value;
  }
  equals(other) {
    return (
      this === other || (other instanceof Custom && this.value === other.value)
    );
  }
}
// true
is(new Custom(0), new Custom(0));
// false
is(new Custom(0), new Custom(1));

Changelog:

v1.2.1 (01/04/2024)

  • Update dependencies

You Might Be Interested In:


Leave a Reply