isBlank.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. export default function isBlank(value) {
  2. if (_isNil(value)) {
  3. return true
  4. }
  5. switch (checkType(value)) {
  6. case "string":
  7. return value === ""
  8. case "Array":
  9. return value.length === 0
  10. case "Set":
  11. case "Map":
  12. return value.size === 0
  13. default:
  14. return false
  15. }
  16. function checkType(value) {
  17. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
  18. if (value === null) {
  19. return "null"
  20. }
  21. const baseType = typeof value
  22. // Primitive types
  23. if (!["object", "function"].includes(baseType)) {
  24. return baseType
  25. }
  26. // Symbol.toStringTag often specifies the "display name" of the
  27. // object's class. It's used in Object.prototype.toString().
  28. const tag = value[Symbol.toStringTag]
  29. if (typeof tag === "string") {
  30. return tag
  31. }
  32. // If it's a function whose source code starts with the "class" keyword
  33. if (
  34. baseType === "function" &&
  35. Function.prototype.toString.call(value)
  36. .startsWith("class")
  37. ) {
  38. return "class"
  39. }
  40. // The name of the constructor; for example `Array`, `GeneratorFunction`,
  41. // `Number`, `String`, `Boolean` or `MyCustomClass`
  42. const className = value.constructor.name
  43. if (typeof className === "string" && className !== "") {
  44. return className
  45. }
  46. // At this point there's no robust way to get the type of value,
  47. // so we use the base implementation.
  48. return baseType
  49. }
  50. }