Skip to content

Test passes for objects that are not equal #42

Closed

Description

@brunerd

The deepequal function has some flaws in it that allows unequal objects to pass a test operation.

I am using jsonpatch.js in my tool jpt and came upon this a few weeks ago. The first tip off was when minifying with Google's Closure Compiler I was getting a warning about unreachable code with the for loop on line 393 and indeed the i++ is never reached because the next line is return on line 340

I went ahead and made my changes to get my tool working as expected, I'll just paste in here, vs. doing a pull request and thanks again @almost for your code it is very helpful for rounding out the features in my JSON power tool! 🙏 :]

function deepEqual(a,b) {
	var key;
	if (a === b) {
		return true;
	} 
	else if(typeof a !== typeof b) {
		return false;
	}
	else if ('object' === typeof(a)) {
		var aIsArray = isArray(a),
		bIsArray = isArray(b);
		if (aIsArray !== bIsArray) {
			return false;
		} 
		else if (aIsArray) {
			// Both are arrays
			if (a.length != b.length) {
				return false;
			} 
			else {
				for (var i = 0; i < a.length; i++) {
					//original code lacked any conditional for return
					if(! deepEqual(a[i], b[i])){
						return false
					}
				}
				return true
			}
		} 
		//Object - the original code was broken
		else {
			//quickly see if they have the same number of objects
			if (Object.keys(a).length !== Object.keys(b).length) { return false }
							
			// Check each key of the object recursively
			for(key in a) {
				if (!b.hasOwnProperty(key) || ! deepEqual(a[key], b[key])) {
					return false;
				}
			}
			return true;
		}
	} 
	else {
		return false;
	}
}

Activity

  1. almost commented on Feb 6, 2022

    @almost
    Member

    Thanks! Wow that's quite a bug to have been hanging around this long. I'll make the fix

  2. added a commit that references this issue on Feb 6, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions