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
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 :
-
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
-
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
The sidebar is recommended
- Crazy blessing! Tencent boss's "million JVM learning notes", real topic of Huawei Java interview 2020-2021
- JS JavaScript how to get the subscript of a value in the array
- How to implement injection in vuex source code?
- JQuery operation select (value, setting, selected)
- One line of code teaches you how to advertise on Tanabata Valentine's Day - Animation 3D photo album (music + text) HTML + CSS + JavaScript
- An article disassembles the pyramid architecture behind the gamefi outbreak
- BEM - a front-end CSS naming methodology
- [vue3] encapsulate custom global plug-ins
- Error using swiper plug-in in Vue
- Another ruthless character fell by 40000, which was "more beautiful" than Passat and maiteng, and didn't lose BMW
guess what you like
-
Huang Lei basks in Zhang Yixing's album, and the relationship between teachers and apprentices is no less than that in the past. Netizens envy Huang Lei
-
He was cheated by Wang Xiaofei and Li Chengxuan successively. Is an Yixuan a blessed daughter and not a blessed home?
-
Zhou Shen sang the theme song of the film "summer friends and sunny days" in mainland China. Netizen: endless aftertaste
-
Pink is Wangyuan online! Back to the peak! The new hairstyle is creamy and sassy
-
Front end interview daily 3 + 1 - day 858
-
Spring Webflux tutorial: how to build reactive web applications
-
[golang] walk into go language lesson 24 TCP high-level operation
-
August 23, 2021 Daily: less than three years after its establishment, Google dissolved the health department
-
The female doctor of Southeast University is no less beautiful than the female star. She has been married four times, and her personal experience has been controversial
-
There are many potential safety hazards in Chinese restaurant. The top of the program recording shed collapses, and the artist will fall down if he is careless
Random recommended
- Anti Mafia storm: He Yun's helpless son, Sun Xing, is destined to be caught by his dry son
- Introduction to flex flexible layout in CSS -- learning notes
- CSS learning notes - Flex layout (Ruan Yifeng tutorial summary)
- Today, let's talk about the arrow function of ES6
- Some thoughts on small program development
- Talk about mobile terminal adaptation
- Unwilling to cooperate with Wang Yibo again, Zhao Liying's fans went on a collective strike and made a public apology in less than a day
- JS function scope, closure, let, const
- Zheng Shuang's 30th birthday is deserted. Chen Jia has been sending blessings for ten years. Is it really just forgetting to make friends?
- Unveil the mystery of ascension
- Asynchronous solution async await
- Analysis and expansion of Vue infinite scroll source code
- Compression webpack plugin first screen loading optimization
- Specific usage of vue3 video play plug-in
- "The story of huiyeji" -- people are always greedy, and fairies should be spotless!
- Installing Vue devtool for chrome and Firefox
- Basic usage of JS object
- 1. JavaScript variable promotion mechanism
- Two easy-to-use animation JS that make the page move
- Front end Engineering - scaffold
- Java SQL Server intelligent fixed asset management, back end + front end + mobile end
- Mediator pattern of JavaScript Design Pattern
- Array de duplication problem solution - Nan recognition problem
- New choice for app development: building mobile applications using Vue native
- New gs8 Chengdu auto show announces interior Toyota technology blessing
- Vieira officially terminated his contract and left the team. The national security club sent blessings to him
- Less than 200000 to buy a Ford RV? 2.0T gasoline / diesel power, horizontal bed / longitudinal bed layout can be selected
- How does "heart 4" come to an end? Pinhole was boycotted by the brand, Ma Dong deleted the bad comments, and no one blessed him
- We are fearless in epidemic prevention and control -- pay tribute to the front-line workers of epidemic prevention!
- Front end, netty framework tutorial
- Xiaomi 11 | miui12.5 | android11 solves the problem that the httpcanary certificate cannot be installed
- The wireless charging of SAIC Roewe rx5 plus is so easy to use!
- Upload and preview pictures with JavaScript, and summarize the most complete mybatis core configuration file
- [25] typescript
- CSS transform Complete Guide (Second Edition) flight.archives 007
- Ajax foundation - HTTP foundation of interview essential knowledge
- Cloud lesson | explain in detail how Huawei cloud exclusive load balancing charges
- Decorator pattern of JavaScript Design Pattern
- [JS] 10. Closure application (loop processing)
- Left hand IRR, right hand NPV, master the password of getting rich