From 3e88e81ec79ae080d15683702d0e21abf45ce49d Mon Sep 17 00:00:00 2001 From: Tom Atkinson Date: Tue, 28 Feb 2017 14:20:39 +0100 Subject: [PATCH] perf(*): Performance improvements (#3) - Remove inner function - Return early for primitive types - Check Array before Buffer as this is both more common and faster --- index.js | 59 ++++++++++++++++++++++++++++---------------------------- 1 file changed, 29 insertions(+), 30 deletions(-) diff --git a/index.js b/index.js index 434ccfa..9e8ade0 100644 --- a/index.js +++ b/index.js @@ -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; }