- Source:
Trait to check whether two values are equal.a
const {equals, eq, uneq, assertEquals, assertUneq} = require('ferrum');
// Implementing this type
class Bar {
constructor(foo, bang) {
this.foo = foo;
this.bang = bang;
}
[Equals.sym](a, b) {
return b instanceof Bar
&& eq(a.foo, b.foo)
&& eq(a.bang, b.bang);
}
}
// Or alternatively
Equals.impl(Bar, (a, b) => {
...
});
// Test for equality
eq(new Bar(42, 23), new Bar(42, 23)); // => true
eq(new Bar(42, 23), new Bar(0, 0)); // => falseAA
uneq(4, 3); // => true
uneq(4, 4); // => false
assertEquals({}, {}, 'Values where different!'); // OK!
assertEquals({}, {foo: 42}, 'Values where different!'); // Assertion Error!
assertUneq([], [{}], 'Values where the same'); // OK!
assertUneq([], [], 'Values where the same'); // Assertion Error!
Normally this trait should not be used directly; consider using
eq() instead.
This trait should be used only in cases where ===/is() is too
strict. Equals is for cases in which the content of two variables
or data structures is the same/semantically equivalent.
Interface
(value1: Any, value2: Any) => r: Boolean
Laws
Equals.invoke(a, b) <=> Equals.invoke(b, a)
This law seems trivial at first, but one actually needs to take some
care to make this work: The trait resolves to the implementation for
the first argument!
So Equals.invoke(a: Number, b: String) and Equals.invoke(a: String, b: Number)
will actually resolve to two different implementations.
The easiest way to make this work is just to add a check (a, b) => type(b) === Number
to the implementation for number and adding an equivalent check in string.
If comparing across types is actually desired (and might return true),
I suggest using the same code for both implementations: Consider the following
contrive examples:
Equals.impl(Number, (a, b) =>
type(b) === (String || type(b) === Number)
&& a.toString() === b.toString());
Equals.impl(String, (a, b) =>
type(b) === (String || type(b) === Number)
&& a.toString() === b.toString());
Specialization notes
Extra implementations provided for Date, RegExp, URL and typed arrays.
Note that for sets: eq(new Set([{}]), new Set([{}])) does not hold true,
since in sets keys and values are the same thing and keys always follow ===
semantics.
See: eq See: uneq See: assertEquals See: assertUneq