general.ts 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. import { makeMap } from './makeMap'
  2. export const EMPTY_OBJ: { readonly [key: string]: any } = __DEV__
  3. ? Object.freeze({})
  4. : {}
  5. export const EMPTY_ARR = __DEV__ ? Object.freeze([]) : []
  6. export const NOOP = () => {}
  7. /**
  8. * Always return false.
  9. */
  10. export const NO = () => false
  11. export const isOn = (key: string) =>
  12. key.charCodeAt(0) === 111 /* o */ &&
  13. key.charCodeAt(1) === 110 /* n */ &&
  14. // uppercase letter
  15. (key.charCodeAt(2) > 122 || key.charCodeAt(2) < 97)
  16. export const isModelListener = (key: string) => key.startsWith('onUpdate:')
  17. export const extend = Object.assign
  18. export const remove = <T>(arr: T[], el: T) => {
  19. const i = arr.indexOf(el)
  20. if (i > -1) {
  21. arr.splice(i, 1)
  22. }
  23. }
  24. const hasOwnProperty = Object.prototype.hasOwnProperty
  25. export const hasOwn = (
  26. val: object,
  27. key: string | symbol,
  28. ): key is keyof typeof val => hasOwnProperty.call(val, key)
  29. export const isArray = Array.isArray
  30. export const isMap = (val: unknown): val is Map<any, any> =>
  31. toTypeString(val) === '[object Map]'
  32. export const isSet = (val: unknown): val is Set<any> =>
  33. toTypeString(val) === '[object Set]'
  34. export const isDate = (val: unknown): val is Date =>
  35. toTypeString(val) === '[object Date]'
  36. export const isRegExp = (val: unknown): val is RegExp =>
  37. toTypeString(val) === '[object RegExp]'
  38. export const isFunction = (val: unknown): val is Function =>
  39. typeof val === 'function'
  40. export const isString = (val: unknown): val is string => typeof val === 'string'
  41. export const isSymbol = (val: unknown): val is symbol => typeof val === 'symbol'
  42. export const isObject = (val: unknown): val is Record<any, any> =>
  43. val !== null && typeof val === 'object'
  44. export const isPromise = <T = any>(val: unknown): val is Promise<T> => {
  45. return (
  46. (isObject(val) || isFunction(val)) &&
  47. isFunction((val as any).then) &&
  48. isFunction((val as any).catch)
  49. )
  50. }
  51. export const objectToString = Object.prototype.toString
  52. export const toTypeString = (value: unknown): string =>
  53. objectToString.call(value)
  54. export const toRawType = (value: unknown): string => {
  55. // extract "RawType" from strings like "[object RawType]"
  56. return toTypeString(value).slice(8, -1)
  57. }
  58. export const isPlainObject = (val: unknown): val is object =>
  59. toTypeString(val) === '[object Object]'
  60. export const isIntegerKey = (key: unknown) =>
  61. isString(key) &&
  62. key !== 'NaN' &&
  63. key[0] !== '-' &&
  64. '' + parseInt(key, 10) === key
  65. export const isReservedProp = /*#__PURE__*/ makeMap(
  66. // the leading comma is intentional so empty string "" is also included
  67. ',key,ref,ref_for,ref_key,' +
  68. 'onVnodeBeforeMount,onVnodeMounted,' +
  69. 'onVnodeBeforeUpdate,onVnodeUpdated,' +
  70. 'onVnodeBeforeUnmount,onVnodeUnmounted',
  71. )
  72. export const isBuiltInDirective = /*#__PURE__*/ makeMap(
  73. 'bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo',
  74. )
  75. const cacheStringFunction = <T extends (str: string) => string>(fn: T): T => {
  76. const cache: Record<string, string> = Object.create(null)
  77. return ((str: string) => {
  78. const hit = cache[str]
  79. return hit || (cache[str] = fn(str))
  80. }) as T
  81. }
  82. const camelizeRE = /-(\w)/g
  83. /**
  84. * @private
  85. */
  86. export const camelize = cacheStringFunction((str: string): string => {
  87. return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''))
  88. })
  89. const hyphenateRE = /\B([A-Z])/g
  90. /**
  91. * @private
  92. */
  93. export const hyphenate = cacheStringFunction((str: string) =>
  94. str.replace(hyphenateRE, '-$1').toLowerCase(),
  95. )
  96. /**
  97. * @private
  98. */
  99. export const capitalize = cacheStringFunction(<T extends string>(str: T) => {
  100. return (str.charAt(0).toUpperCase() + str.slice(1)) as Capitalize<T>
  101. })
  102. /**
  103. * @private
  104. */
  105. export const toHandlerKey = cacheStringFunction(<T extends string>(str: T) => {
  106. const s = str ? `on${capitalize(str)}` : ``
  107. return s as T extends '' ? '' : `on${Capitalize<T>}`
  108. })
  109. // compare whether a value has changed, accounting for NaN.
  110. export const hasChanged = (value: any, oldValue: any): boolean =>
  111. !Object.is(value, oldValue)
  112. export const invokeArrayFns = (fns: Function[], arg?: any) => {
  113. for (let i = 0; i < fns.length; i++) {
  114. fns[i](arg)
  115. }
  116. }
  117. export const def = (
  118. obj: object,
  119. key: string | symbol,
  120. value: any,
  121. writable = false,
  122. ) => {
  123. Object.defineProperty(obj, key, {
  124. configurable: true,
  125. enumerable: false,
  126. writable,
  127. value,
  128. })
  129. }
  130. /**
  131. * "123-foo" will be parsed to 123
  132. * This is used for the .number modifier in v-model
  133. */
  134. export const looseToNumber = (val: any): any => {
  135. const n = parseFloat(val)
  136. return isNaN(n) ? val : n
  137. }
  138. /**
  139. * Only concerns number-like strings
  140. * "123-foo" will be returned as-is
  141. */
  142. export const toNumber = (val: any): any => {
  143. const n = isString(val) ? Number(val) : NaN
  144. return isNaN(n) ? val : n
  145. }
  146. // for typeof global checks without @types/node
  147. declare var global: {}
  148. let _globalThis: any
  149. export const getGlobalThis = (): any => {
  150. return (
  151. _globalThis ||
  152. (_globalThis =
  153. typeof globalThis !== 'undefined'
  154. ? globalThis
  155. : typeof self !== 'undefined'
  156. ? self
  157. : typeof window !== 'undefined'
  158. ? window
  159. : typeof global !== 'undefined'
  160. ? global
  161. : {})
  162. )
  163. }
  164. const identRE = /^[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/
  165. export function genPropsAccessExp(name: string) {
  166. return identRE.test(name)
  167. ? `__props.${name}`
  168. : `__props[${JSON.stringify(name)}]`
  169. }