Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

comparator for custom equality checks #187

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -63,6 +63,9 @@ bower install jsdiff --save

* `JsDiff.diffArrays(oldArr, newArr[, options])` - diffs two arrays, comparing each item for strict equality (===).

Options
* `comparator`: `function(left, right)` for custom equality checks

Returns a list of change objects (See below).

* `JsDiff.createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader)` - creates a unified diff patch.
11 changes: 9 additions & 2 deletions src/diff/base.js
Original file line number Diff line number Diff line change
@@ -144,8 +144,15 @@ Diff.prototype = {
},

equals(left, right) {
return left === right
|| (this.options.ignoreCase && left.toLowerCase() === right.toLowerCase());
if (this.options.comparator) {
if (Array.isArray(right)) {
right = right[0];
}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is this array lookup doing? Is there a case where arrays are passed in here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes there is some edge case - maybe because of how this lib uses tokenize() and join()

arrayDiff.tokenize = arrayDiff.join = function(value) {
  return value.slice();
};

return this.options.comparator(left, right);
} else {
return left === right
|| (this.options.ignoreCase && left.toLowerCase() === right.toLowerCase());
}
},
removeEmpty(array) {
let ret = [];
15 changes: 15 additions & 0 deletions test/diff/array.js
Original file line number Diff line number Diff line change
@@ -15,5 +15,20 @@ describe('diff/array', function() {
{count: 1, value: [c], removed: true, added: undefined}
]);
});

it('Should diff arrays with comparator', function() {
const a = {a: 0}, b = {a: 1}, c = {a: 2}, d = {a: 3};
function comparator(left, right) {
return left.a === right.a;
}
const diffResult = diffArrays([a, b, c], [a, b, d], { comparator: comparator });
console.log(diffResult);
expect(diffResult).to.deep.equals([
{count: 2, value: [a, b]},
{count: 1, value: [c], removed: true, added: undefined},
{count: 1, value: [d], removed: undefined, added: true}
]);
});

});
});