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 sametextand the same answers. - Two
Answers are equal when they have the sametext.
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 questionOneconst questionTwo = {text: "Who you gonna call?",answers: [{text: "Ghostbusters"},{text: "Better Call Saul"}]};// same text but different answersconst questionThree = {text: "Who you gonna call?",answers: [{text: "Ghostbusters"}]};console.log(questionOne === questionTwo) // falseconsole.log(eqQuestion.equals(questionOne, questionTwo)); // true!console.log(eqQuestion.equals(questionTwo, questionThree)); // false