Skip to content

Instantly share code, notes, and snippets.

@skylord123
Last active February 22, 2017 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skylord123/e595f97516e979c40905657527844c46 to your computer and use it in GitHub Desktop.
Save skylord123/e595f97516e979c40905657527844c46 to your computer and use it in GitHub Desktop.
Associative array helpers
/**
*
* @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