一, 当前环境的一系列判断
1.1 inBrowser: 检测当前宿主环境是否是浏览器
// 通过判断 `window` 对象是否存在即可
export const inBrowser = typeof window !== 'undefined'
1.2 hasProto:检查当前环境是否可以使用对象的 __proto__ 属性
// 一个对象的 __proto__ 属性指向了其构造函数的原型
// 从一个空的对象字面量开始沿着原型链逐级检查。
export const hasProto = '__proto__' in {}
二. 字符串操作
2.1 isReserved:检测字符串是否以 $ 或者 _ 开头
// charCodeAt() 方法可返回指定位置的字符的 Unicode 编码
export function isReserved (str: string): boolean {
const c = (str + '').charCodeAt(0)
return c === 0x24 || c === 0x5F
}
2.2 camelize: 连字符转驼峰
const camelizeRE = /-(\w)/g
export const camelize = cached((str: string): string => {
return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '')
})
2.3 capitalize:首字符大写
// 忽略cached
export const capitalize = cached((str: string): string => {
return str.charAt(0).toUpperCase() + str.slice(1)
})
2.4 hyphenate:驼峰转连字符
const hyphenateRE = /\B([A-Z])/g
export const hyphenate = cached((str: string): string => {
return str.replace(hyphenateRE, '-$1').toLowerCase()
})
三. 类型判断
3.1 isPrimitive: 判断变量是否为原型类型
export function isPrimitive (value: any): boolean %checks {
return (
typeof value === 'string' ||
typeof value === 'number' ||
// $flow-disable-line
typeof value === 'symbol' ||
typeof value === 'boolean'
)
}
3.2 isRegExp: 判断变量是否为正则对象
// 使用 Object.prototype.toString 与 '[object RegExp]' 做全等对比。
export function isRegExp (v: any): boolean {
return _toString.call(v) === '[object RegExp]'
}