What is microdiff?
The microdiff npm package is a lightweight utility for calculating the differences between two JavaScript objects. It is designed to be fast and efficient, making it suitable for applications where performance is critical.
What are microdiff's main functionalities?
Basic Object Diffing
This feature allows you to find the differences between two simple objects. The code sample demonstrates how to use microdiff to compare two objects and log the differences.
const diff = require('microdiff');
const obj1 = { a: 1, b: 2 };
const obj2 = { a: 1, b: 3 };
const differences = diff(obj1, obj2);
console.log(differences);
Nested Object Diffing
This feature allows you to find differences in nested objects. The code sample shows how microdiff can be used to compare nested objects and identify changes at any level of depth.
const diff = require('microdiff');
const obj1 = { a: 1, b: { c: 2, d: 3 } };
const obj2 = { a: 1, b: { c: 2, d: 4 } };
const differences = diff(obj1, obj2);
console.log(differences);
Array Diffing
This feature allows you to find differences between arrays. The code sample demonstrates how microdiff can be used to compare two arrays and log the differences.
const diff = require('microdiff');
const arr1 = [1, 2, 3];
const arr2 = [1, 2, 4];
const differences = diff(arr1, arr2);
console.log(differences);
Other packages similar to microdiff
deep-diff
The deep-diff package provides similar functionality to microdiff, allowing you to find differences between two JavaScript objects. It supports nested objects and arrays, but it is generally larger and may not be as performant as microdiff.
diff
The diff package is a more general-purpose diffing library that can be used to find differences between strings, arrays, and objects. It is more feature-rich than microdiff but also larger and potentially slower for object diffing.
just-diff
The just-diff package is another lightweight library for diffing JavaScript objects. It is similar in size and performance to microdiff, but it may have a different API and feature set.
Microdiff
Microdiff is a tiny (currently <1kb), fast, zero dependency object and array comparison library. It is significantly faster than most other deep comparison libraries, and has full TypeScript support.
Get started
First, install Microdiff
npm i microdiff
Then, simply import it and run it on two objects.
import diff from "microdiff";
const obj1 = {
originalProperty: true,
};
const obj2 = {
originalProperty: true,
newProperty: "new",
};
console.log(diff(obj1, obj2));
There are three different types of changes. CREATE
, REMOVE
, and CHANGE
. The path
property gives a path to the property in the new object (or the old object in the case of REMOVE
). Each element in the array is a key to the next property a level deeper until you get to the property changed. The value
property exists in types CREATE
and CHANGE
, and it contains the value of the property added/changed.