diff --git a/index.js b/index.js index 395036e..c4cdc97 100644 --- a/index.js +++ b/index.js @@ -10,7 +10,9 @@ var isArray = require('isarray'); * Module exports. */ -module.exports = hasBinary; +module.exports = function hasBinaryCircular (obj) { + return hasBinary(obj, []); +}; /** * Checks for binary data. @@ -21,14 +23,20 @@ module.exports = hasBinary; * @api public */ -function hasBinary (obj) { +function hasBinary (obj, known) { if (!obj || typeof obj !== 'object') { return false; } + if (known.indexOf(obj) >= 0) { + return false; + } + + known.push(obj); + if (isArray(obj)) { for (var i = 0, l = obj.length; i < l; i++) { - if (hasBinary(obj[i])) { + if (hasBinary(obj[i], known)) { return true; } } @@ -45,11 +53,11 @@ function hasBinary (obj) { // see: https://github.com/Automattic/has-binary/pull/4 if (obj.toJSON && typeof obj.toJSON === 'function') { - return hasBinary(obj.toJSON()); + return hasBinary(obj.toJSON(), known); } for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) { + if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key], known)) { return true; } } diff --git a/test.js b/test.js index 8e65ff3..127fac5 100644 --- a/test.js +++ b/test.js @@ -79,4 +79,29 @@ describe('has-binarydata', function () { assert(!hasBinary(global.Blob)); }); } + + it('should work with recursive structures and no blobs', function () { + var child = { + foo: 'bar' + }; + var parent = { + zoo: 'gar', + child: child + }; + child.parent = parent; + assert(!hasBinary(child)); + }); + + it('should work with recursive structures and blobs', function () { + var child = { + foo: 'bar' + }; + var parent = { + zoo: 'gar', + child: child, + blob: new Buffer('xxx') + }; + child.parent = parent; + assert(hasBinary(child)); + }); });