当前环境

  • inBrowser: 检查当前环境是否是浏览器
    // 通过判断 `window` 对象是否存在即可
    export const inBrowser = typeof window !== 'undefined'
    
  • hasProto: 检查当前环境是否可以使用对象的__proto__属性
    // 一个对象的 __proto__ 属性指向了其构造函数的原型。从一个空的对象字面量开始沿着原型链逐级检查。
    export const hasProto = '__proto__' in {}
    

字符串操作

  • isReserved: 检查字符串是否以$或者_开头
    // charCodeAt() 方法可返回指定位置的字符的 Unicode 编码
    export function isReserved(str) {
      const c = (str + '').charCodeAt(0)
      return c === 0x24 || c === 0x5f
    }
    
  • camelize: 连字符转驼峰
    const camelizeRE = /-(\w)/g
    export const camelize = cached((str) => {
      return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''))
    })
    
  • capitalize: 首字符大写
    // 忽略cached
    export const capitalize = cached((str) => {
      return str.charAt(0).toUpperCase() + str.slice(1)
    })
    
  • hyhenate: 驼峰转连字符
    const hyphenateRE = /\B([A-Z])/g
    export const hyphenate = cached((str) => {
      return str.replace(hyphenateRE, '-$1').toLowerCase()
    })
    

类型判断

  • isPrimitive: 判断变量是否为原始类型
    export function isPrimitive(value) {
      return (
        typeof value === 'string' ||
        typeof value === 'number' ||
        // $flow-disable-line
        typeof value === 'symbol' ||
        typeof value === 'boolean'
      )
    }
    
  • isRegExp: 判断变量是否为正则对象
    // 使用 Object.prototype.toString 与 '[object RegExp]' 做全等对比
    export function isRegExp(v: any): boolean {
      return _toString.call(v) === '[object RegExp]'
    }