Skip to content

Commit

Permalink
perf(*): Performance improvements (#3)
Browse files Browse the repository at this point in the history
- Remove inner function
- Return early for primitive types
- Check Array before Buffer as this is both more common and faster
  • Loading branch information
Tom Atkinson authored and darrachequesne committed Feb 28, 2017
1 parent 73875a2 commit 3e88e81
Showing 1 changed file with 29 additions and 30 deletions.
59 changes: 29 additions & 30 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,46 +14,45 @@ module.exports = hasBinary;
/**
* Checks for binary data.
*
* Right now only Buffer and ArrayBuffer are supported..
* Supports Buffer, ArrayBuffer, Blob and File.
*
* @param {Object} anything
* @api public
*/

function hasBinary(data) {
function hasBinary(obj) {

function _hasBinary(obj) {
if (!obj) return false;
if (!obj || typeof obj !== 'object') {
return false;
}

if ( (global.Buffer && global.Buffer.isBuffer && global.Buffer.isBuffer(obj)) ||
(global.ArrayBuffer && obj instanceof ArrayBuffer) ||
(global.Blob && obj instanceof Blob) ||
(global.File && obj instanceof File)
) {
return true;
if (isArray(obj)) {
for (var i = 0, l = obj.length; i < l; i++) {
if (hasBinary(obj[i])) {
return true;
}
}
return false;
}

if (isArray(obj)) {
for (var i = 0; i < obj.length; i++) {
if (_hasBinary(obj[i])) {
return true;
}
}
} else if (obj && 'object' == typeof obj) {
// see: https://github.com/Automattic/has-binary/pull/4
if (obj.toJSON && 'function' == typeof obj.toJSON) {
obj = obj.toJSON();
}

for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
return true;
}
}
}
if ( (global.Buffer && global.Buffer.isBuffer && global.Buffer.isBuffer(obj)) ||
(global.ArrayBuffer && obj instanceof ArrayBuffer) ||
(global.Blob && obj instanceof Blob) ||
(global.File && obj instanceof File)
) {
return true;
}

return false;
// see: https://github.com/Automattic/has-binary/pull/4
if (obj.toJSON && 'function' == typeof obj.toJSON) {
obj = obj.toJSON();
}

for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
return true;
}
}

return _hasBinary(data);
return false;
}

0 comments on commit 3e88e81

Please sign in to comment.