util.js 7.8 KB

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