util.ts 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. export const emptyObject: Record<string, any> = Object.freeze({})
  2. export const isArray = Array.isArray
  3. // These helpers produce better VM code in JS engines due to their
  4. // explicitness and function inlining.
  5. export function isUndef(v: any): v is undefined | null {
  6. return v === undefined || v === null
  7. }
  8. export function isDef<T>(v: T): v is NonNullable<T> {
  9. return v !== undefined && v !== null
  10. }
  11. export function isTrue(v: any): boolean {
  12. return v === true
  13. }
  14. export function isFalse(v: any): boolean {
  15. return v === false
  16. }
  17. /**
  18. * Check if value is primitive.
  19. */
  20. export function isPrimitive(value: any): boolean {
  21. return (
  22. typeof value === 'string' ||
  23. typeof value === 'number' ||
  24. // $flow-disable-line
  25. typeof value === 'symbol' ||
  26. typeof value === 'boolean'
  27. )
  28. }
  29. /**
  30. * Quick object check - this is primarily used to tell
  31. * objects from primitive values when we know the value
  32. * is a JSON-compliant type.
  33. */
  34. export function isObject(obj: any): boolean {
  35. return obj !== null && typeof obj === 'object'
  36. }
  37. /**
  38. * Get the raw type string of a value, e.g., [object Object].
  39. */
  40. const _toString = Object.prototype.toString
  41. export function toRawType(value: any): string {
  42. return _toString.call(value).slice(8, -1)
  43. }
  44. /**
  45. * Strict object type check. Only returns true
  46. * for plain JavaScript objects.
  47. */
  48. export function isPlainObject(obj: any): boolean {
  49. return _toString.call(obj) === '[object Object]'
  50. }
  51. export function isRegExp(v: any): v is RegExp {
  52. return _toString.call(v) === '[object RegExp]'
  53. }
  54. /**
  55. * Check if val is a valid array index.
  56. */
  57. export function isValidArrayIndex(val: any): boolean {
  58. const n = parseFloat(String(val))
  59. return n >= 0 && Math.floor(n) === n && isFinite(val)
  60. }
  61. export function isPromise(val: any): boolean {
  62. return (
  63. isDef(val) &&
  64. typeof val.then === 'function' &&
  65. typeof val.catch === 'function'
  66. )
  67. }
  68. /**
  69. * Convert a value to a string that is actually rendered.
  70. */
  71. export function toString(val: any): string {
  72. return val == null
  73. ? ''
  74. : Array.isArray(val) || (isPlainObject(val) && val.toString === _toString)
  75. ? JSON.stringify(val, null, 2)
  76. : String(val)
  77. }
  78. /**
  79. * Convert an input value to a number for persistence.
  80. * If the conversion fails, return original string.
  81. */
  82. export function toNumber(val: string): number | string {
  83. const n = parseFloat(val)
  84. return isNaN(n) ? val : n
  85. }
  86. /**
  87. * Make a map and return a function for checking if a key
  88. * is in that map.
  89. */
  90. export function makeMap(
  91. str: string,
  92. expectsLowerCase?: boolean
  93. ): (key: string) => true | undefined {
  94. const map = Object.create(null)
  95. const list: Array<string> = str.split(',')
  96. for (let i = 0; i < list.length; i++) {
  97. map[list[i]] = true
  98. }
  99. return expectsLowerCase ? val => map[val.toLowerCase()] : val => map[val]
  100. }
  101. /**
  102. * Check if a tag is a built-in tag.
  103. */
  104. export const isBuiltInTag = makeMap('slot,component', true)
  105. /**
  106. * Check if an attribute is a reserved attribute.
  107. */
  108. export const isReservedAttribute = makeMap('key,ref,slot,slot-scope,is')
  109. /**
  110. * Remove an item from an array.
  111. */
  112. export function remove(arr: Array<any>, item: any): Array<any> | void {
  113. if (arr.length) {
  114. const index = arr.indexOf(item)
  115. if (index > -1) {
  116. return arr.splice(index, 1)
  117. }
  118. }
  119. }
  120. /**
  121. * Check whether an object has the property.
  122. */
  123. const hasOwnProperty = Object.prototype.hasOwnProperty
  124. export function hasOwn(obj: Object | Array<any>, key: string): boolean {
  125. return hasOwnProperty.call(obj, key)
  126. }
  127. /**
  128. * Create a cached version of a pure function.
  129. */
  130. export function cached<R>(fn: (str: string) => R): (sr: string) => R {
  131. const cache: Record<string, R> = Object.create(null)
  132. return function cachedFn(str: string) {
  133. const hit = cache[str]
  134. return hit || (cache[str] = fn(str))
  135. }
  136. }
  137. /**
  138. * Camelize a hyphen-delimited string.
  139. */
  140. const camelizeRE = /-(\w)/g
  141. export const camelize = cached((str: string): string => {
  142. return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''))
  143. })
  144. /**
  145. * Capitalize a string.
  146. */
  147. export const capitalize = cached((str: string): string => {
  148. return str.charAt(0).toUpperCase() + str.slice(1)
  149. })
  150. /**
  151. * Hyphenate a camelCase string.
  152. */
  153. const hyphenateRE = /\B([A-Z])/g
  154. export const hyphenate = cached((str: string): string => {
  155. return str.replace(hyphenateRE, '-$1').toLowerCase()
  156. })
  157. /**
  158. * Simple bind polyfill for environments that do not support it,
  159. * e.g., PhantomJS 1.x. Technically, we don't need this anymore
  160. * since native bind is now performant enough in most browsers.
  161. * But removing it would mean breaking code that was able to run in
  162. * PhantomJS 1.x, so this must be kept for backward compatibility.
  163. */
  164. /* istanbul ignore next */
  165. function polyfillBind(fn: Function, ctx: Object): Function {
  166. function boundFn(a: any) {
  167. const l = arguments.length
  168. return l
  169. ? l > 1
  170. ? fn.apply(ctx, arguments)
  171. : fn.call(ctx, a)
  172. : fn.call(ctx)
  173. }
  174. boundFn._length = fn.length
  175. return boundFn
  176. }
  177. function nativeBind(fn: Function, ctx: Object): Function {
  178. return fn.bind(ctx)
  179. }
  180. // @ts-expect-error bind cannot be `undefined`
  181. export const bind = Function.prototype.bind ? nativeBind : polyfillBind
  182. /**
  183. * Convert an Array-like object to a real Array.
  184. */
  185. export function toArray(list: any, start?: number): Array<any> {
  186. start = start || 0
  187. let i = list.length - start
  188. const ret: Array<any> = new Array(i)
  189. while (i--) {
  190. ret[i] = list[i + start]
  191. }
  192. return ret
  193. }
  194. /**
  195. * Mix properties into target object.
  196. */
  197. export function extend(
  198. to: Record<PropertyKey, any>,
  199. _from?: Record<PropertyKey, any>
  200. ): Record<PropertyKey, any> {
  201. for (const key in _from) {
  202. to[key] = _from[key]
  203. }
  204. return to
  205. }
  206. /**
  207. * Merge an Array of Objects into a single Object.
  208. */
  209. export function toObject(arr: Array<any>): object {
  210. const res = {}
  211. for (let i = 0; i < arr.length; i++) {
  212. if (arr[i]) {
  213. extend(res, arr[i])
  214. }
  215. }
  216. return res
  217. }
  218. /* eslint-disable no-unused-vars */
  219. /**
  220. * Perform no operation.
  221. * Stubbing args to make Flow happy without leaving useless transpiled code
  222. * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/).
  223. */
  224. export function noop(a?: any, b?: any, c?: any) {}
  225. /**
  226. * Always return false.
  227. */
  228. export const no = (a?: any, b?: any, c?: any) => false
  229. /* eslint-enable no-unused-vars */
  230. /**
  231. * Return the same value.
  232. */
  233. export const identity = (_: any) => _
  234. /**
  235. * Generate a string containing static keys from compiler modules.
  236. */
  237. export function genStaticKeys(modules: Array<ModuleOptions>): string {
  238. return modules
  239. .reduce((keys, m) => {
  240. return keys.concat(m.staticKeys || [])
  241. }, [] as string[])
  242. .join(',')
  243. }
  244. /**
  245. * Check if two values are loosely equal - that is,
  246. * if they are plain objects, do they have the same shape?
  247. */
  248. export function looseEqual(a: any, b: any): boolean {
  249. if (a === b) return true
  250. const isObjectA = isObject(a)
  251. const isObjectB = isObject(b)
  252. if (isObjectA && isObjectB) {
  253. try {
  254. const isArrayA = Array.isArray(a)
  255. const isArrayB = Array.isArray(b)
  256. if (isArrayA && isArrayB) {
  257. return (
  258. a.length === b.length &&
  259. a.every((e: any, i: any) => {
  260. return looseEqual(e, b[i])
  261. })
  262. )
  263. } else if (a instanceof Date && b instanceof Date) {
  264. return a.getTime() === b.getTime()
  265. } else if (!isArrayA && !isArrayB) {
  266. const keysA = Object.keys(a)
  267. const keysB = Object.keys(b)
  268. return (
  269. keysA.length === keysB.length &&
  270. keysA.every(key => {
  271. return looseEqual(a[key], b[key])
  272. })
  273. )
  274. } else {
  275. /* istanbul ignore next */
  276. return false
  277. }
  278. } catch (e: any) {
  279. /* istanbul ignore next */
  280. return false
  281. }
  282. } else if (!isObjectA && !isObjectB) {
  283. return String(a) === String(b)
  284. } else {
  285. return false
  286. }
  287. }
  288. /**
  289. * Return the first index at which a loosely equal value can be
  290. * found in the array (if value is a plain object, the array must
  291. * contain an object of the same shape), or -1 if it is not present.
  292. */
  293. export function looseIndexOf(arr: Array<unknown>, val: unknown): number {
  294. for (let i = 0; i < arr.length; i++) {
  295. if (looseEqual(arr[i], val)) return i
  296. }
  297. return -1
  298. }
  299. /**
  300. * Ensure a function is called only once.
  301. */
  302. export function once(fn: Function): Function {
  303. let called = false
  304. return function () {
  305. if (!called) {
  306. called = true
  307. fn.apply(this, arguments)
  308. }
  309. }
  310. }