is-binary.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. const withNativeArrayBuffer = typeof ArrayBuffer === "function";
  2. const isView = (obj) => {
  3. return typeof ArrayBuffer.isView === "function"
  4. ? ArrayBuffer.isView(obj)
  5. : obj.buffer instanceof ArrayBuffer;
  6. };
  7. const toString = Object.prototype.toString;
  8. const withNativeBlob = typeof Blob === "function" ||
  9. (typeof Blob !== "undefined" &&
  10. toString.call(Blob) === "[object BlobConstructor]");
  11. const withNativeFile = typeof File === "function" ||
  12. (typeof File !== "undefined" &&
  13. toString.call(File) === "[object FileConstructor]");
  14. /**
  15. * Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File.
  16. *
  17. * @private
  18. */
  19. export function isBinary(obj) {
  20. return ((withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj))) ||
  21. (withNativeBlob && obj instanceof Blob) ||
  22. (withNativeFile && obj instanceof File));
  23. }
  24. export function hasBinary(obj, toJSON) {
  25. if (!obj || typeof obj !== "object") {
  26. return false;
  27. }
  28. if (Array.isArray(obj)) {
  29. for (let i = 0, l = obj.length; i < l; i++) {
  30. if (hasBinary(obj[i])) {
  31. return true;
  32. }
  33. }
  34. return false;
  35. }
  36. if (isBinary(obj)) {
  37. return true;
  38. }
  39. if (obj.toJSON &&
  40. typeof obj.toJSON === "function" &&
  41. arguments.length === 1) {
  42. return hasBinary(obj.toJSON(), true);
  43. }
  44. for (const key in obj) {
  45. if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
  46. return true;
  47. }
  48. }
  49. return false;
  50. }