deepDiffer: add maxDepth arg

Reviewed By: blairvanderhoof

Differential Revision: D7839729

fbshipit-source-id: fe9a06d2aaed9dfbfb3e52779ba4b1b98007b9ce
This commit is contained in:
Spencer Ahrens 2018-05-01 21:53:22 -07:00 committed by Facebook Github Bot
parent 5b2a2bee7a
commit fffae99640
2 changed files with 18 additions and 3 deletions

View File

@ -98,4 +98,16 @@ describe('deepDiffer', function() {
var obj = [1,[2,3]];
expect(deepDiffer(obj, obj)).toBe(false);
});
it('should respect maxDepth arg', () => {
expect(deepDiffer(
{a: {A: {aA: 1, bB: 1}}, b: 1},
{a: {A: {aA: 1, bB: 1}}, b: 1},
3
)).toBe(true);
expect(deepDiffer(
{a: {A: {aA: 1, bB: 1}}, b: 1},
{a: {A: {aA: 1, bB: 1}}, b: 1},
4
)).toBe(false);
});
});

View File

@ -11,7 +11,10 @@
/*
* @returns {bool} true if different, false if equal
*/
var deepDiffer = function(one: any, two: any): bool {
var deepDiffer = function(one: any, two: any, maxDepth: number = -1): bool {
if (maxDepth === 0) {
return true;
}
if (one === two) {
// Short circuit on identical object references instead of traversing them.
return false;
@ -39,13 +42,13 @@ var deepDiffer = function(one: any, two: any): bool {
return true;
}
for (var ii = 0; ii < len; ii++) {
if (deepDiffer(one[ii], two[ii])) {
if (deepDiffer(one[ii], two[ii], maxDepth - 1)) {
return true;
}
}
} else {
for (var key in one) {
if (deepDiffer(one[key], two[key])) {
if (deepDiffer(one[key], two[key], maxDepth - 1)) {
return true;
}
}