vue源码中的检测方法

摘要:判断是否为undefined或null; 判断是否为Promise 函数;判断是否为简单数据类型;严格检查复杂数据类型;将驼峰字符串转成连接符 magicEightTall 转换成 magic-eight-tall

// 判断是否为undefined或null

const isDef = (v) => {
  return v !== undefined && v !== null
}


// 判断是否为Promise 函数

const isPromise = (val) => {
  return (
    val !== undefine &&
    typeof val.then === 'function' &&
    typeof val.catch === 'function'
  )
}


// 判断是否为简单数据类型

const isPrimitive (value) => {
  return (
    typeof value === 'string' ||
    typeof value === 'number' ||
    typeof value === 'symbol' ||
    typeof value === 'boolean'
  )
}


// 严格检查复杂数据类型

const isPlainObject = (obj) => {
  return Object.prototype.toString.call(obj) === '[object Object]'
}

const isRegExp = (v) => {
  return Object.prototype.toString.call(v) === '[object RegExp]'
}


// 将驼峰字符串转成连接符 magicEightTall 转换成 magic-eight-tall

const hyphenateRE = /\B([A-Z])/g
const hyphenate = (str) => {
  return str.replace(hyphenateRE, '-$1').toLowerCase()
}


// 将连接符转成驼峰字符串 magic-eight-tall 转换成 magicEightTall

const camelizeRE = /-(\w)/g
const camelize = (str) => {
    return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '')
}


// 如果不想重复转换,可用以下方法调用转换函数

const cached = (fn) => {
    const cache = Object.create(null)
    console.log(cache);
    return ((str) => {
      const hit = cache[str]
      return hit || (cache[str] = fn(str))
    })
};

// 例
const camelize = cached((str) => {
    return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '')
})

本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://shenqiku.cn/article/FLY_5531