Skip to content

Instantly share code, notes, and snippets.

@rdeavila
Forked from oodavid/dump.js
Created March 27, 2014 14:22
Show Gist options
  • Save rdeavila/9808633 to your computer and use it in GitHub Desktop.
Save rdeavila/9808633 to your computer and use it in GitHub Desktop.
/**
* DUMP
*
* Dumps a variable in a readable form to the console, this is a recursive function
* so be careful of nested references that may cause it to overflow... (untested for that)
*
* @v ANYTHING [Any variable]
* @name STRING [The name of the variable, optional, used internally when looping objects and arrays]
* @spacing STRING [The prefix spacing, used internally when looping objects and arrays]
*/
var dump = function(v, name, spacing){
var n;
// Default the spacing to none (incremented on subsequent calls)
spacing = spacing || '';
// If we've been given a name, append a ": "
name = name ? name + ': ' : '';
// Figure out the type, fixes for NULL and ARRAY
var type = typeof v;
if(type == 'object'){
if(v === null){
type = 'null';
} else if(Object.prototype.toString.call(v) === '[object Array]'){
type = 'array';
}
}
// Switch the type
switch(type){
case 'number':
console.log(spacing + name + '[Num] ' + v);
break;
case 'string':
console.log(spacing + name + '[Str] ' + v);
break;
case 'boolean':
console.log(spacing + name + '[Boo] ' + v);
break;
case 'null':
console.log(spacing + name + '[Nul] ' + v);
break;
case 'undefined':
console.log(spacing + name + '[Und] ' + v);
break;
case 'object':
console.log(spacing + name + '[Obj] {');
for(n in v){
dump(v[n], n, (spacing+' '));
}
console.log(spacing + '}');
break;
case 'array':
console.log(spacing + name + '[Arr] (');
for(n in v){
dump(v[n], n, (spacing+' '));
}
console.log(spacing + ')');
break;
}
};
dump('string');
[Str] string
dump(123);
[Num] 123
dump([ 1, 2, 'a', 'b', null, true, false ]);
[Arr] (
0: [Num] 1
1: [Num] 2
2: [Str] a
3: [Str] b
4: [Nul] null
5: [Boo] true
6: [Boo] false
)
dump({ 'a': 1, 'b': 2, 'c': null, false: true, 'ar': [ 1, 2, 3, null ] });
[Obj] {
a: [Num] 1
b: [Num] 2
c: [Nul] null
false: [Boo] true
ar: [Arr] (
0: [Num] 1
1: [Num] 2
2: [Num] 3
3: [Nul] null
)
}
dump(null);
[Nul] null
dump();
[Und] undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment