util.js 5.7 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3
const _toString = Object.prototype.toString
const hasOwnProperty = Object.prototype.hasOwnProperty

4 5 6 7
const _completeValue = value => {
  return value > 9 ? value : ('0' + value)
}

fxy060608's avatar
fxy060608 已提交
8 9 10
export function isFn (fn) {
  return typeof fn === 'function'
}
fxy060608's avatar
fxy060608 已提交
11 12 13 14 15

export function isStr (str) {
  return typeof str === 'string'
}

16 17 18 19
export function isObject (obj) {
  return obj !== null && typeof obj === 'object'
}

fxy060608's avatar
fxy060608 已提交
20 21 22 23 24 25 26 27
export function isPlainObject (obj) {
  return _toString.call(obj) === '[object Object]'
}

export function hasOwn (obj, key) {
  return hasOwnProperty.call(obj, key)
}

28
export function noop () {}
fxy060608's avatar
fxy060608 已提交
29 30 31 32 33

export function toRawType (val) {
  return _toString.call(val).slice(8, -1)
}

fxy060608's avatar
fxy060608 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
/**
 * Create a cached version of a pure function.
 */
export function cached (fn) {
  const cache = Object.create(null)
  return function cachedFn (str) {
    const hit = cache[str]
    return hit || (cache[str] = fn(str))
  }
}

/**
 * Camelize a hyphen-delimited string.
 */
const camelizeRE = /-(\w)/g
export const camelize = cached((str) => {
  return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '')
})
52 53 54 55 56 57 58

/**
 * Capitalize a string.
 */
export const capitalize = cached((str) => {
  return str.charAt(0).toUpperCase() + str.slice(1)
})
fxy060608's avatar
fxy060608 已提交
59

fxy060608's avatar
fxy060608 已提交
60 61 62 63 64 65 66 67
export function setProperties (item, props, propsData) {
  props.forEach(function (name) {
    if (hasOwn(propsData, name)) {
      item[name] = propsData[name]
    }
  })
}

fxy060608's avatar
fxy060608 已提交
68
export function getLen (str = '') {
fxy060608's avatar
fxy060608 已提交
69 70
  /* eslint-disable no-control-regex */
  return ('' + str).replace(/[^\x00-\xff]/g, '**').length
71 72 73 74 75 76 77 78 79 80 81
}

export function formatDateTime ({
  date = new Date(),
  mode = 'date'
}) {
  if (mode === 'time') {
    return _completeValue(date.getHours()) + ':' + _completeValue(date.getMinutes())
  } else {
    return date.getFullYear() + '-' + _completeValue(date.getMonth() + 1) + '-' + _completeValue(date.getDate())
  }
fxy060608's avatar
fxy060608 已提交
82
}
83 84

export function updateElementStyle (element, styles) {
fxy060608's avatar
fxy060608 已提交
85
  for (const attrName in styles) {
86 87
    element.style[attrName] = styles[attrName]
  }
fxy060608's avatar
init v3  
fxy060608 已提交
88 89 90 91
}

export function guid () {
  return Math.floor(4294967296 * (1 + Math.random())).toString(16).slice(1)
fxy060608's avatar
fxy060608 已提交
92 93 94 95
}

export function debounce (fn, delay) {
  let timeout
96
  const newFn = function () {
fxy060608's avatar
fxy060608 已提交
97 98 99 100
    clearTimeout(timeout)
    const timerFn = () => fn.apply(this, arguments)
    timeout = setTimeout(timerFn, delay)
  }
101 102 103 104 105 106 107 108 109
  newFn.cancel = function () {
    clearTimeout(timeout)
  }
  return newFn
}

export function throttle (fn, wait) {
  let last = 0
  let timeout
110
  let waitCallback
111 112 113
  const newFn = function (...arg) {
    const now = Date.now()
    clearTimeout(timeout)
114 115
    waitCallback = () => {
      waitCallback = null
116 117 118 119 120 121 122 123 124 125 126
      last = now
      fn.apply(this, arg)
    }
    if (now - last < wait) {
      timeout = setTimeout(waitCallback, wait - (now - last))
      return
    }
    waitCallback()
  }
  newFn.cancel = function () {
    clearTimeout(timeout)
127 128 129 130 131
    waitCallback = null
  }
  newFn.flush = function () {
    clearTimeout(timeout)
    waitCallback && waitCallback()
132 133
  }
  return newFn
Q
qiang 已提交
134 135 136 137
}

export function kebabCase (string) {
  return string.replace(/[A-Z]/g, str => '-' + str.toLowerCase())
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
}

/**
 * Check if two values are loosely equal - that is,
 * if they are plain objects, do they have the same shape?
 */
export function looseEqual (a, b) {
  if (a === b) return true
  const isObjectA = isObject(a)
  const isObjectB = isObject(b)
  if (isObjectA && isObjectB) {
    try {
      const isArrayA = Array.isArray(a)
      const isArrayB = Array.isArray(b)
      if (isArrayA && isArrayB) {
        return a.length === b.length && a.every((e, i) => {
          return looseEqual(e, b[i])
        })
      } else if (a instanceof Date && b instanceof Date) {
        return a.getTime() === b.getTime()
      } else if (!isArrayA && !isArrayB) {
        const keysA = Object.keys(a)
        const keysB = Object.keys(b)
        return keysA.length === keysB.length && keysA.every(key => {
          return looseEqual(a[key], b[key])
        })
      } else {
        /* istanbul ignore next */
        return false
      }
    } catch (e) {
      /* istanbul ignore next */
      return false
    }
  } else if (!isObjectA && !isObjectB) {
    return String(a) === String(b)
  } else {
    return false
  }
}

export function deepClone (vnodes, createElement) {
  function cloneVNode (vnode) {
    var clonedChildren = vnode.children && vnode.children.map(cloneVNode)
    var cloned = createElement(vnode.tag, vnode.data, clonedChildren)
    cloned.text = vnode.text
    cloned.isComment = vnode.isComment
    cloned.componentOptions = vnode.componentOptions
    cloned.elm = vnode.elm
    cloned.context = vnode.context
    cloned.ns = vnode.ns
    cloned.isStatic = vnode.isStatic
    cloned.key = vnode.key
    return cloned
  }

  return vnodes.map(cloneVNode)
}
雪洛's avatar
雪洛 已提交
196 197

export * from './uni-id-mixin'
D
DCloud_LXH 已提交
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225

export function IEVersion () {
  const userAgent = navigator.userAgent
  const isIE = userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1
  const isEdge = userAgent.indexOf('Edge') > -1 && !isIE
  const isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf('rv:11.0') > -1
  if (isIE) {
    const reIE = new RegExp('MSIE (\\d+\\.\\d+);')
    reIE.test(userAgent)
    const fIEVersion = parseFloat(RegExp.$1)
    if (fIEVersion > 6) {
      return fIEVersion
    } else {
      return 6
    }
  } else if (isEdge) {
    return -1
  } else if (isIE11) {
    return 11
  } else {
    return -1
  }
}

export function getDeviceBrand (model) {
  if (/iphone/gi.test(model) || /ipad/gi.test(model) || /mac/gi.test(model)) { return 'apple' }
  if (/windows/gi.test(model)) { return 'microsoft' }
}