Codesnacks

moon indicating dark mode
sun indicating light mode

Compare objects using Eq type class

April 11, 2020

Want to check if two domain models are logically equal? We can achieve this by implementing instances of the Eq type class for our domain models [1].

Comparison can be

  • abstract / strict (==, ===) [2]
  • or structural

The following snippet shows how to use structural comparison. Note that comparison by identity could also be implementing like this.

Rules for equality of our models:

  • Two Questions are equal when they have the same text and the same answers.
  • Two Answers are equal when they have the same text.
import { Eq, getStructEq, eqString } from "fp-ts/lib/Eq";
import { getEq } from "fp-ts/lib/Array";
interface Question {
text: string;
answers: Answer[];
}
interface Answer {
text: string;
}
const eqAnswer: Eq<Answer> = getStructEq({
text: eqString
});
const eqQuestion: Eq<Question> = getStructEq({
text: eqString,
answers: getEq(eqAnswer)
});
const questionOne = {
text: "Who you gonna call?",
answers: [
{
text: "Ghostbusters"
},
{
text: "Better Call Saul"
}
]
};
// same properties as questionOne
const questionTwo = {
text: "Who you gonna call?",
answers: [
{
text: "Ghostbusters"
},
{
text: "Better Call Saul"
}
]
};
// same text but different answers
const questionThree = {
text: "Who you gonna call?",
answers: [
{
text: "Ghostbusters"
}
]
};
console.log(questionOne === questionTwo) // false
console.log(eqQuestion.equals(questionOne, questionTwo)); // true!
console.log(eqQuestion.equals(questionTwo, questionThree)); // false

Further Readings


A collection of some small code snippets & experiments
No tutorials. Nothing fancy. Just some code.