系列文章目录

  1. 目录分析
  2. 初始化流程
  3. 响应式系统
  4. shared工具函数


前言

封装工具函数,可以高效地进行开发,提高开发效率。
packages/shared目录就是存放工具函数的包,下面来看看有哪些基础函数值得我们借鉴学习~


1、数组中移除某元素

export const remove = <T>(arr: T[], el: T) => {
  const i = arr.indexOf(el)
  if (i > -1) {
    arr.splice(i, 1)
  }
}

2、字符串转数字

export const toNumber = (val: any): any => {
  const n = parseFloat(val);     // 可解析一个字符串,并返回一个浮点数。如果字符串的第一个字符不能被转换为数字,那么 parseFloat() 会返回 NaN
  return isNaN(n) ? val : n;     // 判定n为'NaN'情况
}

3、转为字符串

export const objectToString = Object.prototype.toString
export const toTypeString = (value: unknown): string =>
  objectToString.call(value)

4、判定值是否发生改变

// compare whether a value has changed, accounting for NaN.
export const hasChanged = (value: any, oldValue: any): boolean =>
  value !== oldValue && (value === value || oldValue === oldValue)
  • value !== oldValue 比较新旧值不等
  • (value === value || oldValue === oldValue) 这主要是针对值是NaN的情况

5、判定数据类型

5.1 数组
export const isArray = Array.isArray
5.2 Map
export const isSet = (val: unknown): val is Set<any> =>
  toTypeString(val) === '[object Map]'
5.3 Set
export const isSet = (val: unknown): val is Set<any> =>
  toTypeString(val) === '[object Set]'
5.4 Date
export const isDate = (val: unknown): val is Date => val instanceof Date
5.5 function、string、symbol
export const isFunction = (val: unknown): val is Function =>
  typeof val === 'function'
  
export const isString = (val: unknown): val is string => typeof val === 'string'

export const isSymbol = (val: unknown): val is symbol => typeof val === 'symbol'
5.6 object
export const isObject = (val: unknown): val is Record<any, any> =>
  val !== null && typeof val === 'object'
5.7 plain object

Plain Object:纯粹的对象(通过 “{}” 或者 “new Object” 创建的)

export const isPlainObject = (val: unknown): val is object =>
  toTypeString(val) === '[object Object]'
5.8 Promise
export const isPromise = <T = any>(val: unknown): val is Promise<T> => {
  return isObject(val) && isFunction(val.then) && isFunction(val.catch)
}

总结

未完待续~

Logo

前往低代码交流专区

更多推荐