-
Notifications
You must be signed in to change notification settings - Fork 21
Equality
emmanueltouzery edited this page Nov 20, 2018
·
5 revisions
prelude-ts offers some helper functions to implement the equals
and
hashCode
functions for your own objects:
fieldsHashCode
and areEqual.
Here is an example of object using these helpers:
class MyClass {
constructor(private field1:string, private field2:number) {}
equals(other: MyClass): boolean {
if (!other) {
return false;
}
return areEqual(this.field1, other.field1) &&
areEqual(this.field2, other.field2);
}
hashCode(): number {
return fieldsHashCode(this.field1, this.field2);
}
toString(): string {
return `{field1: ${this.field1}, field2: ${this.field2}}`;
}
}
Be careful, equals
could be called with a parameter being in fact of another type,
so if the field names you compare with are too generic (like id
), maybe put
a marker to disambiguate the type.
But again, equals
and hashCode
are not required by prelude.ts, except for Set
and Map
keys.