Skip to content

Commit 3e88e81

Browse files
Tom Atkinsondarrachequesne
Tom Atkinson
authored andcommittedFeb 28, 2017
perf(*): Performance improvements (#3)
- Remove inner function - Return early for primitive types - Check Array before Buffer as this is both more common and faster
1 parent 73875a2 commit 3e88e81

File tree

1 file changed

+29
-30
lines changed

1 file changed

+29
-30
lines changed
 

Diff for: ‎index.js

+29-30
Original file line numberDiff line numberDiff line change
@@ -14,46 +14,45 @@ module.exports = hasBinary;
1414
/**
1515
* Checks for binary data.
1616
*
17-
* Right now only Buffer and ArrayBuffer are supported..
17+
* Supports Buffer, ArrayBuffer, Blob and File.
1818
*
1919
* @param {Object} anything
2020
* @api public
2121
*/
2222

23-
function hasBinary(data) {
23+
function hasBinary(obj) {
2424

25-
function _hasBinary(obj) {
26-
if (!obj) return false;
25+
if (!obj || typeof obj !== 'object') {
26+
return false;
27+
}
2728

28-
if ( (global.Buffer && global.Buffer.isBuffer && global.Buffer.isBuffer(obj)) ||
29-
(global.ArrayBuffer && obj instanceof ArrayBuffer) ||
30-
(global.Blob && obj instanceof Blob) ||
31-
(global.File && obj instanceof File)
32-
) {
33-
return true;
29+
if (isArray(obj)) {
30+
for (var i = 0, l = obj.length; i < l; i++) {
31+
if (hasBinary(obj[i])) {
32+
return true;
33+
}
3434
}
35+
return false;
36+
}
3537

36-
if (isArray(obj)) {
37-
for (var i = 0; i < obj.length; i++) {
38-
if (_hasBinary(obj[i])) {
39-
return true;
40-
}
41-
}
42-
} else if (obj && 'object' == typeof obj) {
43-
// see: https://github.com/Automattic/has-binary/pull/4
44-
if (obj.toJSON && 'function' == typeof obj.toJSON) {
45-
obj = obj.toJSON();
46-
}
47-
48-
for (var key in obj) {
49-
if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
50-
return true;
51-
}
52-
}
53-
}
38+
if ( (global.Buffer && global.Buffer.isBuffer && global.Buffer.isBuffer(obj)) ||
39+
(global.ArrayBuffer && obj instanceof ArrayBuffer) ||
40+
(global.Blob && obj instanceof Blob) ||
41+
(global.File && obj instanceof File)
42+
) {
43+
return true;
44+
}
5445

55-
return false;
46+
// see: https://github.com/Automattic/has-binary/pull/4
47+
if (obj.toJSON && 'function' == typeof obj.toJSON) {
48+
obj = obj.toJSON();
49+
}
50+
51+
for (var key in obj) {
52+
if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
53+
return true;
54+
}
5655
}
5756

58-
return _hasBinary(data);
57+
return false;
5958
}

0 commit comments

Comments
 (0)