2
0

util.ts 8.8 KB

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