Last active
February 22, 2017 19:24
-
-
Save skylord123/e595f97516e979c40905657527844c46 to your computer and use it in GitHub Desktop.
Associative array helpers
This file contains 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
/** | |
* | |
* @param a | |
* @param b | |
* @param options | |
* ignoreMissingKeys (false) => if true will only compare keys that exist in both objects. | |
* caseSensitive (true) => if false strings will be compared without case sensitivity | |
* boolComparison (false) => if true will also compare using the Boolean values (helps match empty strings '' and NULL for example) | |
* @returns {boolean} | |
*/ | |
Sithous.prototype.compareAssociativeArrays = function(a, b, options) { | |
var defaultOptions = { | |
'ignoreMissingKeys': false, | |
'caseSensitive': true, | |
'boolComparison': false | |
}; | |
options = $.extend({}, defaultOptions, typeof options == 'object' ? options : {}); | |
var nrKeysFunction = function(a) { | |
return $.isArray(a) ? a.length : Object.keys(a).length; | |
}; | |
if (a == b) { | |
return true; | |
} | |
if(!options.ignoreMissingKeys) { | |
if (nrKeysFunction(a) != nrKeysFunction(b)) { | |
return false; | |
} | |
} | |
for (var akey in a) { | |
if(!a.hasOwnProperty(akey)) { | |
continue; | |
} | |
var value = a[akey], | |
value2 = b[akey]; | |
if(options.ignoreMissingKeys && (typeof value == 'undefined' || typeof value2 == 'undefined')) { | |
continue; | |
} | |
if (!options.caseSensitive && typeof value == 'string' && typeof value2 == 'string') { | |
if(value.toLowerCase() != value2.toLowerCase()) { | |
return false; | |
} | |
} else if (value != value2 && (options.boolComparison && Boolean(value) !== Boolean(value2))) { | |
return false; | |
} | |
} | |
return true; | |
}; | |
/** | |
* Loop over an Array/Object and see if the object needle is in there (uses compareAssociativeArrays for comparison) | |
* @param array | |
* @param needle | |
* @param options | |
* @returns {*} | |
*/ | |
Sithous.prototype.findMatchingAssociativeArray = function(array, needle, options) { | |
for(var i in array) { | |
if(!array.hasOwnProperty(i)) continue; | |
if(this.compareAssociativeArrays(array[i], needle, options)) { | |
return i; | |
} | |
} | |
return null; | |
}; | |
// Initiate Sithous object | |
var sithous = new Sithous(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment