Skip to content

Commit

Permalink
working browser example
Browse files Browse the repository at this point in the history
  • Loading branch information
James Halliday committed Jul 26, 2013
0 parents commit 34be6b6
Show file tree
Hide file tree
Showing 3 changed files with 94 additions and 0 deletions.
7 changes: 7 additions & 0 deletions example/inspect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
var inspect = require('../');

var d = document.createElement('div');
d.setAttribute('id', 'beep');
d.innerHTML = '<b>wooo</b><i>iiiii</i>';

console.log(inspect([ d, { a: 3, b : 4, c: [5,6,[7,[8,[9]]]] } ]));
62 changes: 62 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
module.exports = function inspect_ (obj, opts, depth) {
if (!opts) opts = {};
var maxDepth = opts.depth || 5;

if (depth === undefined) depth = 0;
if (depth > maxDepth) return '...';

function inspect (value) {
return inspect_(value, opts, depth + 1);
}

if (typeof obj === 'string') {
return "'" + obj.replace(/(['\\])/g, '\\$1') + "'";
}
else if (typeof HTMLElement !== 'undefined' && obj instanceof HTMLElement) {
var s = '<' + String(obj.tagName).toLowerCase();
var attrs = obj.attributes || [];
for (var i = 0; i < attrs.length; i++) {
s += ' ' + attrs[i].name + '="' + quote(attrs[i].value) + '"';
}
s += '>';
if (obj.childNodes && obj.childNodes.length) s += '...';
s += '</' + String(obj.tagName).toLowerCase() + '>';
return s;
}
else if (isArray(obj)) {
var xs = Array(obj.length);
for (var i = 0; i < obj.length; i++) {
xs[i] = inspect(obj[i]);
}
return '[ ' + xs.join(', ') + ' ]';
}
else if (typeof obj === 'object' && !isDate(obj) && !isRegExp(obj)) {
var xs = [];
for (var key in obj) {
if ({}.hasOwnProperty.call(obj, key)) {
if (/[^\w$]/.test(key)) {
xs.push(inspect(key) + ': ' + inspect(obj[key]));
}
else xs.push(key + ': ' + inspect(obj[key]));
}
}
return '{ ' + xs.join(', ') + ' }';
}
else return String(obj);
};

function quote (s) {
return String(s).replace(/"/g, '&quot;');
}

function isArray (obj) {
return {}.toString.call(obj) === '[object Array]';
}

function isDate (obj) {
return {}.toString.call(obj) === '[object Date]';
}

function isRegExp (obj) {
return {}.toString.call(obj) === '[object RegExp]';
}
25 changes: 25 additions & 0 deletions readme.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# object-inspect

inspect objects in node and in the browser

# example

## browser

``` js
var inspect = require('object-inspect');

var d = document.createElement('div');
d.setAttribute('id', 'beep');
d.innerHTML = '<b>wooo</b><i>iiiii</i>';

console.log(inspect([ d, { a: 3, b : 4, c: [5,6,[7,[8,[9]]]] } ]));
```

output:

```
[ <div id="beep">...</div>, { a: 3, b: 4, c: [ 5, 6, [ 7, [ 8, [ ... ] ] ] ] } ]
```

## node

0 comments on commit 34be6b6

Please sign in to comment.