check-types.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. const toString = Object.prototype.toString
  2. const hasOwn = Object.prototype.hasOwnProperty
  3. export const isArray = (arr) => {
  4. return Array.isArray
  5. ? Array.isArray(arr)
  6. : toString.call(arr) === '[object Array]'
  7. }
  8. export const isArrayLike = (obj) =>
  9. obj != null && isLength(obj.length) && !isFunction(obj)
  10. export const isBoolean = (bool) => toString.call(bool) === '[object Boolean]'
  11. export const isDate = (date) => toString.call(date) === '[object Date]'
  12. export const isFunction = (fn) => toString.call(fn) === '[object Function]'
  13. export const isLength = (val) => {
  14. return (
  15. typeof val === 'number' &&
  16. val > -1 &&
  17. val % 1 === 0 &&
  18. val <= Number.MAX_SAFE_INTEGER
  19. )
  20. }
  21. export const isNull = (val) => val === null
  22. export const isUndefined = (val) => val === void 0
  23. export const isNumber = (val) => {
  24. return isNull(val) || isUndefined(val) || isNaN(val) ? false : true
  25. }
  26. export const isObject = (obj) => {
  27. let type = typeof obj
  28. return (obj && (type === 'object' || type === 'function')) || false
  29. }
  30. export const isObjectLike = (obj) => obj != null && typeof obj === 'object'
  31. export const isPlainObject = (obj) => {
  32. if (!isObject(obj) || obj.nodeType || obj === obj.window) {
  33. return false
  34. }
  35. try {
  36. if (
  37. obj.constructor &&
  38. !hasOwn.call(obj, 'constructor') &&
  39. !hasOwn.call(obj.constructor.prototype, 'isPrototypeOf')
  40. ) {
  41. return false
  42. }
  43. } catch (e) {
  44. return false
  45. }
  46. for (var key in obj) {
  47. //
  48. }
  49. return key === void 0 || hasOwn.call(obj, key)
  50. }
  51. export const isRegExp = (reg) => toString.call(reg) === '[object RegExp]'
  52. export const isString = (str) => toString.call(str) === '[object String]'
  53. /**
  54. * 检测一个对象是否是空对象
  55. * 1.对象为null
  56. * 2.数组是空数组
  57. * 3.字面量对象是空对象
  58. * @param {Null|Array|Object} value 检测对象
  59. * @return {Boolean} 返回是否是空对象
  60. */
  61. export const isEmpty = (value) => {
  62. if (value === null) {
  63. return true
  64. }
  65. if (isArray(value)) {
  66. return !value.length
  67. }
  68. if (isPlainObject(value)) {
  69. return !Object.keys(value).length
  70. }
  71. return false
  72. }