Skip to content

Instantly share code, notes, and snippets.

@Error601
Last active August 29, 2015 14:10
Show Gist options
  • Save Error601/d9623b836458b5b6fe86 to your computer and use it in GitHub Desktop.
Save Error601/d9623b836458b5b6fe86 to your computer and use it in GitHub Desktop.
Heavy-handed conversion of JavaScript objects/arrays/functions/strings, etc. to text
/*!
* Convert an object to a string, for whatever reason.
* This can be useful for heavy-handed comparison
* (as in compareByText() function below),
* or printing out JavaScript objects or functions.
*
* Original source:
* http://stackoverflow.com/questions/5612787/converting-an-object-to-a-string
* ('extra' comma issue has been resolved in the code below)
*
* https://gist.github.com/Error601/d9623b836458b5b6fe86
*/
function convertToText( obj, spaces ){
if ( obj === window ) {
// don't be cray-cray
return false
}
var string = '',
part = [],
prop,
len = 0,
i = -1;
// is string - skip all other tests
if ( typeof obj == 'string' ) {
string += obj;
}
// is object
else if ( Object.prototype.toString.call(obj) === '[object Object]' ) {
for ( prop in obj ) {
// should we filter the properties?
//if ( obj.hasOwnProperty(prop) ){
part.push(prop + ': ' + convertToText(obj[prop], spaces));
//}
}
string += ' { ' + part.join(', ') + ' } ';
}
// is array
else if ( Array.isArray(obj) ) {
len = obj.length;
while ( ++i < len ) {
part.push(convertToText(obj[i], spaces));
}
string += ' [ ' + part.join(', ') + ' ]';
}
// is function
else if ( typeof obj == 'function' ) {
string += obj.toString();
}
//all other values can be done with JSON.stringify
else {
string += JSON.stringify(obj);
}
// strip spaces by default and also if (spaces !== true)
if ( typeof spaces == 'undefined' || spaces.toString().toLowerCase() !== 'true' ) {
return string.replace(/\s/g, '');
}
// only keep spaces if (spaces === true)
else {
return string;
}
}
// fairly heavy-handed approach for comparison
function compareByText( obj1, obj2 ){
return convertToText(obj1) === convertToText(obj2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment