Created
August 16, 2018 23:16
-
-
Save snewcomer/74b7e8b469175fdb369c51d8ca9041d7 to your computer and use it in GitHub Desktop.
deep recursive object comparison
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* determine if existing elements for a given `root` || viewportDescriptor have the same observerOptions | |
* We need to test this because two elements may be using the same `root` but have different observerOptions | |
* i.e. viewportTolerance bottom: 500px vs. bottom: 0px | |
* We only compare primitive types and objects; not arrays or functions | |
* | |
* @method _hasSimilarElement | |
*/ | |
_hasSimilarElement(observerOptions, elements) { | |
return elements.some((testElement) => { | |
return this._compareOptions(observerOptions, testElement.observerOptions); | |
}); | |
} | |
/** | |
* @method _compareOptions | |
*/ | |
_compareOptions(observerOptions, elementOptions) { | |
// simple comparison of string, number or even null/undefined | |
let type1 = Object.prototype.toString.call(observerOptions); | |
let type2 = Object.prototype.toString.call(elementOptions); | |
if (type1 !== type2) { | |
return false; | |
} else if (type1 !== '[object Object]' && type2 !== '[object Object]') { | |
return observerOptions === elementOptions; | |
} | |
// complex comparison for only type of [object Object] | |
for (let key in observerOptions) { | |
if (observerOptions.hasOwnProperty(key)) { | |
// recursion to check nested | |
if (this._compareOptions(observerOptions[key], elementOptions[key]) === false) { | |
return false; | |
} | |
} | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment