general.ts 5.9 KB

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