deep-diff、diff、diff-match-patch、diff2html は、すべて「差分(diff)」を扱うライブラリですが、対象データや用途が明確に異なります。deep-diff は JavaScript オブジェクトの構造的な変更を検出するために特化しており、状態管理やデバッグに適しています。diff と diff-match-patch はテキスト文字列の比較に用いられますが、前者は標準的なアルゴリズムを実装し、後者はテキストの編集操作(マッチ・パッチ)まで含む包括的なツールです。diff2html はこれらで生成された差分データを人間が読みやすい HTML 形式に変換する表示層のライブラリです。アーキテクチャ設計においては、データ構造の追跡、テキスト比較、UI 表示のいずれが必要かによって選定が分かれます。
フロントエンド開発において「差分(diff)」を扱う場面は多岐にわたります。状態管理の変更検知、コード比較ツールの実装、あるいは変更履歴の可視化など、用途によって最適なライブラリは全く異なります。deep-diff、diff、diff-match-patch、diff2html は名前が似ていますが、それぞれが解決する課題のレイヤーが明確に区別されています。本稿では、これら 4 つのライブラリを技術的な観点から比較し、実装における適切な選定基準を提供します。
最も重要な区別点は、比較対象が「JavaScript オブジェクト」か「テキスト文字列」かです。
deep-diff は、JavaScript のオブジェクト構造を再帰的に辿り、プロパティの追加・削除・変更を検出します。
// deep-diff: オブジェクトの構造比較
const Diff = require('deep-diff').diff;
const lhs = { name: 'my object' };
const rhs = { name: 'my object', description: 'test' };
const differences = Diff(lhs, rhs);
// 出力: [ { kind: 'N', path: [ 'description' ], rhs: 'test' } ]
// 'N' は新規追加 (New) を意味します
一方、diff、diff-match-patch、diff2html は基本的にテキスト文字列を扱います。
// diff: 文字列の行単位または単語単位の比較
const Diff = require('diff');
const one = 'beep boop';
const other = 'beep booblah';
const changes = Diff.diffChars(one, other);
// 出力: [{count: 4, value: 'beep '}, {count: 4, value: 'boop', removed: true}, ...]
// diff-match-patch: 文字列の差分生成
const dmp = new diff_match_patch();
const text1 = 'The quick brown fox';
const text2 = 'The quick red fox';
const diffs = dmp.diff_main(text1, text2);
// 出力: [[0, 'The quick '], [-1, 'brown'], [1, 'red'], [0, ' fox']]
// 0: 等しい,-1: 削除,1: 追加
// diff2html: 差分文字列(Unified Diff 形式など)を HTML に変換
// 単体で比較は行わず、既存の diff 出力を入力とします
const Diff2Html = require('diff2html').Diff2Html;
const diffInput = `--- a/file.js\n+++ b/file.js\n@@ -1 +1 @@\n-console.log('old');\n+console.log('new');`;
const html = Diff2Html.html(diffInput);
// 出力: 差分を表示するための HTML 文字列
ライブラリが提供する機能の範囲も選定の重要な要素です。
deep-diff と diff は、純粋に「違いを見つける」ことに特化しています。変更を適用する機能は deep-diff に一部存在しますが、主目的は検出です。
// deep-diff: 変更の適用も可能
const applyDiff = require('deep-diff').applyDiff;
const target = { name: 'original' };
const change = { kind: 'E', path: ['name'], lhs: 'original', rhs: 'updated' };
applyDiff(target, [change]);
// target は { name: 'updated' } になる
diff-match-patch は、比較だけでなく「マッチ(類似検索)」と「パッチ(変更適用)」の 3 機能を提供します。これはテキストエディタの共同編集機能などで不可欠です。
// diff-match-patch: パッチの適用
const dmp = new diff_match_patch();
const patches = dmp.patch_make(text1, text2);
const result = dmp.patch_apply(patches, text1);
// 結果: [適用後のテキスト,適用成功かどうかの配列]
diff2html は比較ロジックを持たず、表示に特化しています。git diff や diff ライブラリの出力を、ブラウザでレンダリング可能な HTML に変換します。
// diff2html: 設定オプションによるカスタマイズ
const html = Diff2Html.html(diffInput, {
drawFileList: true,
matching: 'lines',
outputFormat: 'side-by-side'
});
// 左右比較形式の HTML を生成
アルゴリズムの特性を理解することは、大量データを扱う際に重要です。
diff は Myers diff アルゴリズムを実装しており、テキスト行や単語の比較に最適化されています。計算量は O(ND) であり、一般的なコード比較には十分高速です。
// diff: 行単位比較(Myers アルゴリズム)
const diffLines = Diff.diffLines(oldCode, newCode);
diffLines.forEach((part) => {
const color = part.added ? 'green' : part.removed ? 'red' : 'grey';
// 色付け処理など
});
diff-match-patch は、Google によって開発され、人間の入力ミスを許容するようなヒューリスティックな処理が含まれています。完全一致だけでなく、近似一致を探す場合に有利ですが、その分オーバーヘッドがあります。
// diff-match-patch: 近似マッチ
const dmp = new diff_match_patch();
const text = 'The quick brown fox jumps over the lazy dog';
const pattern = 'brown fox';
const match = dmp.match_main(text, pattern, 0);
// 一致するインデックスを返す(完全一致でなくても許容する設定が可能)
deep-diff はオブジェクトの再帰トラバースを行うため、比較対象のオブジェクトが巨大な場合、深さやプロパティ数に比例して処理時間が増加します。循環参照には注意が必要です。
// deep-diff: 循環参照への対策
const differences = Diff(lhs, rhs, (path, key) => {
// 特定のキーを無視するフィルタ
return key === 'timestamp';
});
実際の開発現場では、これらを単独で使うよりも組み合わせて使うことが多くあります。
アプリケーションの状態(オブジェクト)の変化を記録し、タイムトラベルデバッグを実装する場合。
deep-diffユーザーが提交したコードの変更点を Web 上で表示する場合。
diff + diff2htmldiff でコードの文字列比較を行い、その結果を diff2html で見やすく表示する構成が一般的です。// 組み合わせ例
const Diff = require('diff');
const Diff2Html = require('diff2html').Diff2Html;
const diffText = Diff.createTwoFilesPatch('old.js', 'new.js', oldCode, newCode);
const html = Diff2Html.html(diffText);
複数のユーザーが同時にテキストを編集し、変更をマージする場合。
diff-match-patch選定にあたっては、ライブラリのメンテナンス状況も確認する必要があります。
diff-match-patch は非常に歴史のあるライブラリですが、npm パッケージはいくつかのフォークが存在します。公式の Google Code プロジェクトはアーカイブされており、npm で入手可能なパッケージはコミュニティによって維持されているものを指します。新しいプロジェクトでは、よりモダンな代替(例えば Operational Transformation や CRDT を実装したライブラリ)を検討する価値もあります。
diff2html は UI ライブラリであるため、比較ロジックのバグとは切り離して考える必要があります。表示形式の変更(行番号、色テーマなど)は CSS や設定で制御可能です。
// diff2html: CSS クラスのカスタマイズ
// 生成される HTML には固有のクラス名が付与されるため、CSS でスタイルを制御可能
// .d2h-file-header, .d2h-code-line など
| 特徴 | deep-diff | diff | diff-match-patch | diff2html |
|---|---|---|---|---|
| 主な対象 | JavaScript オブジェクト | テキスト文字列 | テキスト文字列 | 差分テキスト (Unified Diff) |
| 主要機能 | 構造比較、変更検出 | 差分生成 (Myers) | 差分、マッチ、パッチ | HTML への変換、可視化 |
| 出力形式 | 変更オブジェクトの配列 | 変更チャンクの配列 | 差分タプル、パッチオブジェクト | HTML 文字列 |
| UI 機能 | なし | なし | なし | あり (シンタックスハイライト等) |
| 典型的用途 | 状態管理、テスト | コード比較、ログ解析 | エディタ、共同編集 | コードレビュー UI |
これら 4 つのライブラリは「差分」という共通のキーワードを持ちながら、技術スタックの異なるレイヤーを担当しています。
データ構造の変更を追跡したいなら deep-diff、テキストの比較ロジックが必要なら diff、高度なテキスト操作まで含めるなら diff-match-patch、そしてそれらをユーザーに見せるなら diff2html を選定してください。
特に注意すべきは、diff2html は比較エンジンではないという点です。よくある間違いとして、diff2html だけで全てを行おうとしますが、実際には diff や git diff の出力を渡す必要があります。また、deep-diff をテキスト比較に使おうとすると、行単位の細かいニュアンスが拾えないため不適切です。
現代のフロントエンドアーキテクチャでは、これらのライブラリを適切に組み合わせることで、堅牢なバージョン管理機能やデバッグツールを比較的短期間で構築できます。それぞれの役割を理解し、目的に合ったツールを配置することが、保守性の高いシステム設計につながります。
JavaScript オブジェクトや配列の深い階層にある変更点を検出したい場合に選択します。状態管理ライブラリの内部実装や、API レスポンスの前後比較など、データ構造そのものの差分が必要なシーンで真価を発揮します。テキスト比較には向かないため、用途を混同しないよう注意が必要です。
標準的なテキスト差分アルゴリズム(Myers diff)を Node.js やブラウザで実行したい場合に選択します。コードレビューツールや、設定ファイルのバージョン比較など、汎用的な文字列比較が必要なプロジェクトで広く使われています。API がシンプルで依存関係も少ないため、軽量な実装に向いています。
単なる比較だけでなく、差分を適用(パッチ)したり、類似テキストを検出(マッチ)したりする機能が必要な場合に選択します。Google によって開発され、共同編集機能やリッチテキストエディタの実装など、複雑なテキスト操作を伴うアプリケーションで採用されています。機能が多岐にわたるため、単純な比較だけならオーバーキルになる可能性があります。
生成された差分データを Web ブラウザ上で美しく可視化したい場合に選択します。diff や git diff の出力を HTML に変換し、シンタックスハイライトや折りたたみ機能を提供します。比較ロジックそのものではなく、UI 表示層のライブラリとして位置づけられ、他の比較ライブラリと組み合わせて使用するのが一般的です。
deep-diff is a javascript/node.js module providing utility functions for determining the structural differences between objects and includes some utilities for applying differences across objects.
npm install deep-diff
Possible v1.0.0 incompatabilities:
deep-diff does a pre-order traversal of the object graph, however, when it encounters an array, the array is processed from the end towards the front, with each element recursively processed in-order during further descent.npm install deep-diff
var diff = require('deep-diff')
// or:
// const diff = require('deep-diff');
// const { diff } = require('deep-diff');
// or:
// const DeepDiff = require('deep-diff');
// const { DeepDiff } = require('deep-diff');
// es6+:
// import diff from 'deep-diff';
// import { diff } from 'deep-diff';
// es6+:
// import DeepDiff from 'deep-diff';
// import { DeepDiff } from 'deep-diff';
<script src="https://cdn.jsdelivr.net/npm/deep-diff@1/dist/deep-diff.min.js"></script>
In a browser,
deep-diffdefines a global variableDeepDiff. If there is a conflict in the global namespace you can restore the conflicting definition and assigndeep-diffto another variable like this:var deep = DeepDiff.noConflict();.
In order to describe differences, change revolves around an origin object. For consistency, the origin object is always the operand on the left-hand-side of operations. The comparand, which may contain changes, is always on the right-hand-side of operations.
var diff = require('deep-diff').diff;
var lhs = {
name: 'my object',
description: 'it\'s an object!',
details: {
it: 'has',
an: 'array',
with: ['a', 'few', 'elements']
}
};
var rhs = {
name: 'updated object',
description: 'it\'s an object!',
details: {
it: 'has',
an: 'array',
with: ['a', 'few', 'more', 'elements', { than: 'before' }]
}
};
var differences = diff(lhs, rhs);
v 0.2.0 and above The code snippet above would result in the following structure describing the differences:
[ { kind: 'E',
path: [ 'name' ],
lhs: 'my object',
rhs: 'updated object' },
{ kind: 'E',
path: [ 'details', 'with', 2 ],
lhs: 'elements',
rhs: 'more' },
{ kind: 'A',
path: [ 'details', 'with' ],
index: 3,
item: { kind: 'N', rhs: 'elements' } },
{ kind: 'A',
path: [ 'details', 'with' ],
index: 4,
item: { kind: 'N', rhs: { than: 'before' } } } ]
Differences are reported as one or more change records. Change records have the following structure:
kind - indicates the kind of change; will be one of the following:
N - indicates a newly added property/elementD - indicates a property/element was deletedE - indicates a property/element was editedA - indicates a change occurred within an arraypath - the property path (from the left-hand-side root)lhs - the value on the left-hand-side of the comparison (undefined if kind === 'N')rhs - the value on the right-hand-side of the comparison (undefined if kind === 'D')index - when kind === 'A', indicates the array index where the change occurreditem - when kind === 'A', contains a nested change record indicating the change that occurred at the array indexChange records are generated for all structural differences between origin and comparand. The methods only consider an object's own properties and array elements; those inherited from an object's prototype chain are not considered.
Changes to arrays are recorded simplistically. We care most about the shape of the structure; therefore we don't take the time to determine if an object moved from one slot in the array to another. Instead, we only record the structural
differences. If the structural differences are applied from the comparand to the origin then the two objects will compare as "deep equal" using most isEqual implementations such as found in lodash or underscore.
When two objects differ, you can observe the differences as they are calculated and selectively apply those changes to the origin object (left-hand-side).
var observableDiff = require('deep-diff').observableDiff;
var applyChange = require('deep-diff').applyChange;
var lhs = {
name: 'my object',
description: 'it\'s an object!',
details: {
it: 'has',
an: 'array',
with: ['a', 'few', 'elements']
}
};
var rhs = {
name: 'updated object',
description: 'it\'s an object!',
details: {
it: 'has',
an: 'array',
with: ['a', 'few', 'more', 'elements', { than: 'before' }]
};
observableDiff(lhs, rhs, function (d) {
// Apply all changes except to the name property...
if (d.path[d.path.length - 1] !== 'name') {
applyChange(lhs, rhs, d);
}
});
A standard import of var diff = require('deep-diff') is assumed in all of the code examples. The import results in an object having the following public properties:
diff(lhs, rhs, prefilter, acc) — calculates the differences between two objects, optionally prefiltering elements for comparison, and optionally using the specified accumulator.observableDiff(lhs, rhs, observer, prefilter) — calculates the differences between two objects and reports each to an observer function, optionally, prefiltering elements for comparison.applyDiff(target, source, filter) — applies any structural differences from a source object to a target object, optionally filtering each difference.applyChange(target, source, change) — applies a single change record to a target object. NOTE: source is unused and may be removed.revertChange(target, source, change) reverts a single change record to a target object. NOTE: source is unused and may be removed.diffThe diff function calculates the difference between two objects.
lhs - the left-hand operand; the origin object.rhs - the right-hand operand; the object being compared structurally with the origin object.prefilter - an optional function that determines whether difference analysis should continue down the object graph.acc - an optional accumulator/array (requirement is that it have a push function). Each difference is pushed to the specified accumulator.Returns either an array of changes or, if there are no changes, undefined. This was originally chosen so the result would be pass a truthy test:
var changes = diff(obja, objb);
if (changes) {
// do something with the changes.
}
The prefilter's signature should be function(path, key) and it should return a truthy value for any path-key combination that should be filtered. If filtered, the difference analysis does no further analysis of on the identified object-property path.
const diff = require('deep-diff');
const assert = require('assert');
const data = {
issue: 126,
submittedBy: 'abuzarhamza',
title: 'readme.md need some additional example prefilter',
posts: [
{
date: '2018-04-16',
text: `additional example for prefilter for deep-diff would be great.
https://stackoverflow.com/questions/38364639/pre-filter-condition-deep-diff-node-js`
}
]
};
const clone = JSON.parse(JSON.stringify(data));
clone.title = 'README.MD needs additional example illustrating how to prefilter';
clone.disposition = 'completed';
const two = diff(data, clone);
const none = diff(data, clone,
(path, key) => path.length === 0 && ~['title', 'disposition'].indexOf(key)
);
assert.equal(two.length, 2, 'should reflect two differences');
assert.ok(typeof none === 'undefined', 'should reflect no differences');
When contributing, keep in mind that it is an objective of deep-diff to have no package dependencies. This may change in the future, but for now, no-dependencies.
Please run the unit tests before submitting your PR: npm test. Hopefully your PR includes additional unit tests to illustrate your change/modification!
When you run npm test, linting will be performed and any linting errors will fail the tests... this includes code formatting.
Thanks to all those who have contributed so far!