current position:Home>Read tool functions in Vue

Read tool functions in Vue

2021-08-27 05:39:22 Front end Engineer

This is my participation 8 The fourth of the yuegengwen challenge 3 God , Check out the activity details :8 Yuegengwen challenge

First, thank you. Ruokawa The organization's source code reading

1.babelParserDefaultPlugins

List three babel plug-in unit

1. Large number

2. Optional chain

3. Controls the merge operator

The second and third are for improving coding happiness , Very useful . It is highly recommended to install

/** * List of @babel/parser plugins that are used for template expression * transforms and SFC script transforms. By default we enable proposals slated * for ES2020. This will need to be updated as the spec moves forward. * Full list at https://babeljs.io/docs/en/next/babel-parser#plugins */
export const babelParserDefaultPlugins = [
  'bigInt',
  'optionalChaining',
  'nullishCoalescingOperator'
] as const
 Copy code 

2.EMPTY_OBJ

export const EMPTY_OBJ: { readonly [key: string]: any } = __DEV__
  ? Object.freeze({})
  : {}
 Copy code 

Returns an empty object ,dev Mode uses Object.freeze This object method .

freeze The main purpose of this method is to freeze objects , But only the first level properties can be frozen , Objects in the object cannot be frozen .

const a = Object.freeze({
    b: 1
})
a.b = 2 //  Can't modify 

const c = Object.freeze({
    b: {
        d: 1
    }
})
c.b.d = 2 //  You can modify 
 Copy code 

Tips: Vue For data that is just displayed in, you can use this API Freeze up , To improve performance

3.EMPTY_ARR

Similar to the above

const EMPTY_ARR = __DEV__ ? Object.freeze([]) : []
 Copy code 

4.NOOP

effect : Returns an empty function

When I see this function, I'm confused ? I think many people have such doubts . After consulting the data, I get the following conclusion :

  1. The default value of the callback function , Reduce judgment

     for example :function test(a, b, cb = Noop) {
        cb()
        //  without Noop When cb() You're going to report a mistake , Or it requires a layer of judgment  cb&&cb()
    }
     Copy code 
  2. Easy code compression

5.No

Never return false

const NO = () => false
 Copy code 

6.isOn

Judge whether it is on At the beginning , It can be used to judge whether it is an event

const onRE = /^on[^a-z]/
export const isOn = (key: string) => onRE.test(key)

isOn('onClick') // true
isOn('onclick') // true
 Copy code 

^ Negation in regular representation , The adult translation is Not in on The beginning is followed by lowercase a-z String

7.isModelListener

Determine whether the string is based on onUpdate: start

const isModelListener = (key: string) => key.startsWith('onUpdate:')
 Copy code 

startsWith New methods for strings and padStart,padEnd,endsWith

8.extend

Object.assign Merge objects , You can see my previous article on objects # Consolidate foundation ( Two )- object

const extend = Object.assign
 Copy code 

9.remove

Remove an item from the array , Don't go into details , There are many ways to do this , For example, using filter

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

10.hasOwn

Determine whether an object has this attribute , Not including... On the prototype chain

const hasOwnProperty = Object.prototype.hasOwnProperty
export const hasOwn = (
  val: object,
  key: string | symbol
): key is keyof typeof val => hasOwnProperty.call(val, key)
 Copy code 

11.isArray

Determine if it's an array

Array.isArray
 Copy code 

12.isMap

Judge whether it is map

export const isMap = (val: unknown): val is Map<any, any> =>
  toTypeString(val) === '[object Map]'
export const isSet = (val: unknown): val is Set<any> =>
  toTypeString(val) === '[object Set]'
 Copy code 

13.isSet

Judge whether it is set

export const isMap = (val: unknown): val is Map<any, any> =>
  toTypeString(val) === '[object Map]'
export const isSet = (val: unknown): val is Set<any> =>
  toTypeString(val) === '[object Set]'
 Copy code 

Use toTypeString Method validation

14.toTypeString

It's actually Object.prototype.toString, Can accurately judge any data type .

export const toTypeString = value =>
  objectToString.call(value)
  
export const objectToString = Object.prototype.toString
 Copy code 

15.isDate

Judge whether it's a date , Use instanceOf Judge ,instanceOf The principle is Instance __proto__ Keep looking up for the existence of xxx.__proto__ Equal to... Of a constructor protoytype

export const isDate = (val: unknown): val is Date => val instanceof Date
 Copy code 

instanceOf simulation

function myInstanceOf (left, right) {
    const rightProto = right.prototype
    let leftVaule = left.__proto__

    while (true) {
        if (leftVaule === null) {
            return false
        } else if (leftVaule === rightProto) {
            return true
        }

        leftVaule = leftVaule.__proto__
    }
}

var temp = {}
var a = {
    name: 1,
    obj: temp
}

var b = Object.create(a)
console.log(b.obj === a.obj)
 Copy code 

16. Judge the basic type

Use typeof Judge .typeof The return value is string, number, boolean, symbol, undefined, function, bigint, object

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'
 Copy code 

17.isObject

Judge whether it is the object ,

export const isObject = (val: unknown): val is Record<any, any> =>
  val !== null && typeof val === 'object'
 Copy code 

18.isPromise

Judge whether it is Promise

export const isPromise = <T = any>(val: unknown): val is Promise<T> => {
  return isObject(val) && isFunction(val.then) && isFunction(val.catch)
}
//  It works here, too  Object.prototype.toString.call Judge , That's why it's written here . I think it's because you can judge custom promise
 Copy code 

19.toRawType

Get specific data types , Because by Object.prototype.toString.call(a) The obtained data type is generally as long as this .[object Promise], adopt .slice(8, -1) You can get... Directly Promise

export const toRawType = (value: unknown): string => {
  // extract "RawType" from strings like "[object RawType]"
  return toTypeString(value).slice(8, -1)
}
 Copy code 

20.isPlainObject

Judge whether it is a pure object

export const isPlainObject = (val: unknown): val is object =>
  toTypeString(val) === '[object Object]'
 Copy code 

21.isIntegerKey

Judge key Is it Decimal Numbers . parseInt The second parameter is Base type

export const isIntegerKey = (key: unknown) =>
  isString(key) &&
  key !== 'NaN' &&
  key[0] !== '-' &&
  '' + parseInt(key, 10) === key
 Copy code 

22.makeMap&&isReservedProp

Determine whether it is a reserved keyword ,makeMap Convert a string to an object map, The value is true


export const isReservedProp = /*#__PURE__*/ makeMap(
  // the leading comma is intentional so empty string "" is also included
  ',key,ref,' +
    'onVnodeBeforeMount,onVnodeMounted,' +
    'onVnodeBeforeUpdate,onVnodeUpdated,' +
    'onVnodeBeforeUnmount,onVnodeUnmounted'
)

export function makeMap( str: string, expectsLowerCase?: boolean ): (key: string) => boolean {
  const map: Record<string, boolean> = Object.create(null)
  const list: Array<string> = str.split(',')
  for (let i = 0; i < list.length; i++) {
    map[list[i]] = true
  }
  return expectsLowerCase ? val => !!map[val.toLowerCase()] : val => !!map[val]
}
 Copy code 

23.cacheStringFunction

Cache function

const cacheStringFunction = <T extends (str: string) => string>(fn: T): T => {
  const cache: Record<string, string> = Object.create(null)
  return ((str: string) => {
    const hit = cache[str]
    return hit || (cache[str] = fn(str))
  }) as any
}

 Copy code 

24.hasChanged

Determine whether two objects change

export const hasChanged = (value: any, oldValue: any): boolean =>
  !Object.is(value, oldValue)
  
const a = {}
const b = a
undefined
const c = Object.assign({}, a)
Object.is(a, b) => true
Object.is(a, c) => false
 Copy code 

25.invokeArrayFns

Execute functions with consistent parameters in the array

export const invokeArrayFns = (fns: Function[], arg?: any) => {
  for (let i = 0; i < fns.length; i++) {
    fns[i](arg)
  }
}
 Copy code 

26.def

Define object properties , Use defineProperty To configure the four properties of the object

export const def = (obj: object, key: string | symbol, value: any) => {
  Object.defineProperty(obj, key, {
    configurable: true,
    enumerable: false,
    value
  })
}

 Copy code 

27.toNumber

convert to number, If it is NaN Output directly , If it's a number, convert it to a number

export const toNumber = (val: any): any => {
  const n = parseFloat(val)
  return isNaN(n) ? val : n
}
 Copy code 

28.getGlobalThis

Get global this, priority of use globalThis, Next is self, And then there was window, And then there was global,node Medium is global,Web Worker  Cannot access  window  object , But we can get through  self  Access to the  Worker  Global objects in the environment .

let _globalThis;
export const getGlobalThis = (): any => {
  return (
    _globalThis ||
    (_globalThis =
      typeof globalThis !== 'undefined'
        ? globalThis
        : typeof self !== 'undefined'
        ? self
        : typeof window !== 'undefined'
        ? window
        : typeof global !== 'undefined'
        ? global
        : {})
  )
}
 Copy code 

The initial implementation is undefined, The second time, there is no need to execute , Direct value .

copyright notice
author[Front end Engineer],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827053918986P.html

Random recommended