Skip to content

Comparing data

To compare things in Javascript, we’re used to using ===:

const word = `hello`;
word === `hello`; // true
const value = 4;
value === 4; // true

This easily breaks down when comparing objects, for example:

const a = { name: `El` };
const b = { name: `El` };
a === b; // false

This is because although the values are the same, the identity of the objects is different. This is especially problematic when using immutable data since the identity of a (logical) object changes every time we alter it.

Ixfx has a few helper functions to compare things.

isEqualValueDefault compares objects by value.

import { isEqualValueDefault } from 'https://unpkg.com/ixfx/dist/util.js';
const a = { name: `El` };
const b = { name: `El` };
isEqualValueDefault(a, b); // true

isEqualValueDefault will return false if the order of properties changes; use isEqualValueIgnoreOrder if this matters.

Change sets

compareData compares two objects, producing a set of changes.

import { compareData } from 'https://unpkg.com/ixfx/dist/data.js';
const a = {
name: `Frank`,
size: 12
}
const b = {
name: `Frank`,
size: 13
}
const changes = compareData(a, b)

Yields:

{
changed: { size:13 },
added: {}, removed: [], children: {},
hasChanged: true, isArray: false,
summary: [
["mutate","size",13]
]
}

If a property is added

import { compareData } from 'https://unpkg.com/ixfx/dist/data.js';
const a = { name: `Frank`, size: 10 }
const b = { name: `Frank`, colour: `red` }
const changes = compareData(a, b)
{
changed:{}, children: {}
added:{ colour:"red" },
removed: ["size"],
hasChanged:true, isArray:false,
summary:[
["del","size",10],
["add","colour","red"]
]
}

More

  • compareArrays - compare array items
  • changedDataFields - treat objects as having the same shape, only looks at values. Throws an error otherwise.
  • compareKeys - compare objects based on properties or keys.