Best JavaScript code snippet using playwright-internal
easy-axios.js
Source:easy-axios.js  
1import axios from 'axios'2import merge from 'lodash/merge'3import { validator } from './validator/validator.js'4import { claim } from './validator/claim.js'5import { toRawType, dataToFormData } from './utils/utils.js'6import { statusMsg } from './constant/statusMsg.js'7import OperationCache from './cache/OperationCache.js'89// EasyAxios é»è®¤ç axios é
ç½®10const defaultAxiosConfig = {11    timeout: 10000,12    responseType: 'json',13    headers: {14        'Content-Type': 'application/json;charset=utf-8',15        'X-Requested-With': 'XMLHttpRequest'16    },17}1819// 妿éè¦å
¼å®¹æ§çé»è¾20export const primevalAxios = axios2122export default class EasyAxios {23    constructor(options = {}, axiosConfig = {}) {24        // éªè¯ options 屿§æ¯å¦åæ³25        const result = validator(options, claim)26        if (result.illegal) throw new Error(result.errorMsg)2728        // è¯·æ±æ°29        this.requestCount = 0 3031        // æ£å¨åéä¸ç请æ±32        this.PendingRequestMap = new Map()3334        // æ¯å¦å¼å¯æç¤º35        this.isOpenTips = toRawType.isBoolean(options.easyAxiosConfig.isOpenTips) ? options.easyAxiosConfig.isOpenTips : false36        37        // æ¯å¦å¼å¯åæ¶éå¤è¯·æ±38        this.isOpenCancelDuplicateRequest = toRawType.isBoolean(options.easyAxiosConfig.isOpenCancelDuplicateRequest) ? options.easyAxiosConfig.isOpenCancelDuplicateRequest : false39        40        // æ¯å¦å¼å¯ç¼å41        this.isOpenRequestCache = toRawType.isBoolean(options.easyAxiosConfig.isOpenRequestCache) ? options.easyAxiosConfig.isOpenRequestCache : false42        43        // ç¼åæ¶é´44        this.cacheEffectiveTime = toRawType.isNumber(options.easyAxiosConfig.cacheEffectiveTime) && options.easyAxiosConfig.cacheEffectiveTime > 1000 * 60 * 5 ? options.easyAxiosConfig.cacheEffectiveTime : 045        46        // æå¤§éè¿æ¬¡æ°47        this.maxReconnectionTimes = toRawType.isNumber(options.easyAxiosConfig.maxReconnectionTimes) ? parseInt(options.easyAxiosConfig.maxReconnectionTimes) : 048        49        // ç¶æç åæä½å½æ°ç对象50        this.statusHandlers = toRawType.isObject(options.easyAxiosConfig.statusHandlers) ? options.easyAxiosConfig.statusHandlers : {}5152        // åéååååºåçå¤ç53        this.beforeRequestHook = toRawType.isFunction(options.beforeRequestHook) ? options.beforeRequestHook : () => {}54        this.afterResponseHook = toRawType.isFunction(options.afterResponseHook) ? options.afterResponseHook : () => {}55        56        // æç¤ºä¿¡æ¯å¤çæ¹æ³57        this.tipsFunction = toRawType.isFunction(options.tipsFunction) ? options.tipsFunction : () => {}58        59        // loading ç¸å
³60        this.startLoading = toRawType.isFunction(options.startLoading) ? options.startLoading : () => {}61        this.endLoading   = toRawType.isFunction(options.endLoading)   ? options.endLoading   : () => {}6263        // è·å response.data 对象éçç¸å
³å±æ§ï¼æ°æ®ãä¿¡æ¯ç ãä¿¡æ¯ï¼64        this.getDataFormResult    = toRawType.isFunction(options.getDataFormResult)    ? options.getDataFormResult    : () => null65        this.getStatusFormResult  = toRawType.isFunction(options.getStatusFormResult)  ? options.getStatusFormResult  : () => null66        this.getMassageFormResult = toRawType.isFunction(options.getMassageFormResult) ? options.getMassageFormResult : () => null6768        // è¯·æ±æ¯å¦æåçéªè¯å¨69        this.validateResultStatus = toRawType.isFunction(options.validateResultStatus) ? options.validateResultStatus : (status) => status >= 200 && status < 3007071        // åå¹¶ axios é
ç½®72        this.config = merge(defaultAxiosConfig, axiosConfig)7374        // å建 axios75        this.createAxios()7677        // å è½½æ¦æªå¨78        this.interceptors()79    }8081    // å建82    createAxios() {83        this.easyAxios = axios.create(this.config)84    }8586    // æ¦æªå¨87    interceptors() {88        // è¯·æ±æ¦æªå¨89        this.easyAxios.interceptors.request.use(90            config => {91                // è¯·æ±æ°èªå¢92                this.requestCount++9394                // è°ç¨å è½½å¨ç»æ¹æ³95                this.startLoading()9697                // èµå¼æä¸æ¥å£æ¯å¦ç¦ç¨ hookãtipsãcache çé
ç½®98                const { easyAxiosConfig: { disableHooks, disableTips, disableCache } = {} } = config99100                // æ¯å¦å¼å¯è¯·æ±ç¼å101                if (this.isOpenRequestCache && !disableCache) {102                    // è·åç¼å103                    const cacheData = EasyAxios.getDataCache(config.method, config.url, config[['get','delete'].includes(config.method.toLocaleLowerCase()) ? 'params' : 'data'])104                    if (cacheData) { // æ¯å¦åå¨105                        return Promise.reject({isOpenRequestCache: true, data: cacheData})106                    }107                }108109                // æ¯å¦è°ç¨ beforeRequestHook110                if (!(disableHooks === true || (disableHooks && disableHooks.request))) {111                    try {112                        this.beforeRequestHook(config)113                    }114                    catch (error) {115                        // è°ç¨æç¤ºæ¹æ³116                        (this.isOpenTips && !disableTips) && this.tipsFunction(`beforeRequestHook å
é¨åºç°é误ï¼${error.message}ï¼è¯·æ£æ¥`)117                    }118                }119120                // ç§»é¤ PendingRequest121                this.removePendingRequest(config)122123                // æ·»å ææ°ç PendingRequest124                this.addPendingRequest(config)125126                return config127            },128            error => {129                // 请æ±åé失败130                (--this.requestCount === 0) && this.endLoading()131132                return Promise.reject(error)133            }134        )135136        // ååºæ¦æªå¨137        this.easyAxios.interceptors.response.use(138            response => {139                // 廿å è½½å¨ç»140                (--this.requestCount === 0) && this.endLoading()141142                // ç§»é¤ PendingRequest143                this.removePendingRequest(response.config)144145                // èµå¼æä¸æ¥å£æ¯å¦ç¦ç¨ hookãtipsãcache çé
ç½®146                const { config: { easyAxiosConfig: { disableHooks, disableTips, disableCache } = {} } } = response147148                // æ¯å¦è°ç¨ afterResponseHook149                if (!(disableHooks === true || (disableHooks && disableHooks.response))) {150                    try {151                        this.afterResponseHook(response, false)152                    }153                    catch (error) {154                        const message = `afterResponseHook å
é¨åºç°é误ï¼${error.message}ï¼è¯·æ£æ¥`155                        156                        // è°ç¨æç¤ºæ¹æ³157                        (this.isOpenTips && !disableTips) && this.tipsFunction(message)158159                        return Promise.reject(message)160                    }161                }162163                // è¿åååºå¯¹è±¡164                return new Promise((resolve, reject) => {165                    if (!response || !response.data) resolve(null)166167                    const resultData = response.data168                    const status = this.getStatusFormResult(resultData) || response.status169170                    if (!this.validateResultStatus(status)) {171                        const message = this.getMassageFormResult(resultData) || statusMsg[status]172                        173                        // è°ç¨æç¤ºæ¹æ³174                        (this.isOpenTips && !disableTips) && this.tipsFunction(message)175176                        const statusHandler = this.statusHandlers[status]177178                        toRawType.isFunction(statusHandler) && statusHandler()179180                        reject(message)181                    }182183                    // è·åæå¡ç«¯è¿åæ°æ®184                    const data = this.getDataFormResult(resultData)185186                    // 设置ç¼åç¸å
³187                    this.isOpenRequestCache 188                    && !disableCache 189                    && EasyAxios.setDataCache(response.config.method, response.config.url, response.config[['get','delete'].includes(response.config.method.toLocaleLowerCase()) ? 'params' : 'data'], data)190          191                    resolve(data)192                })193            },194            error => {195                // 廿å è½½å¨ç»196                (--this.requestCount === 0) && this.endLoading()197198                // æ¯å¦åæ¶éå¤è¯·æ±199                if (axios.isCancel(error)) return Promise.reject(null)200201                // ä»ç¼å䏿¥çï¼è¿åè·åå°çç¼å202                if (toRawType.isBoolean(error.isOpenRequestCache) && error.isOpenRequestCache) return Promise.resolve(error.data)203204                // ç§»é¤ PendingRequest205                this.removePendingRequest(error.config)206207                // èµå¼æä¸æ¥å£æ¯å¦ç¦ç¨ hookãtipsãcache çé
ç½®208                const { config: { easyAxiosConfig: { disableHooks, disableTips } = {} } } = error209                210                // æ¯å¦è°ç¨ afterResponseHook211                if (!(disableHooks === true || (disableHooks && disableHooks.response))) {212                    try {213                        this.afterResponseHook(error, true)214                    } 215                    catch (error) {216                        const message = `afterResponseHook å
é¨åºç°é误ï¼${error.message}ï¼è¯·æ£æ¥`217218                        (this.isOpenTips && !disableTips) && this.tipsFunction(message)219220                        return Promise.reject(message)221                    }222                }223224                if (error.response // ä»
对è¶
æ¶(æ ååº)请æ±è¿è¡éè¯225                || !error.config 226                || this.maxReconnectionTimes < 1 // éè¿æ¬¡æ°å°äº 1 ï¼åä¸éè¦éè¿227                || (error.config.times && error.config.times >= this.maxReconnectionTimes)228                ) {229230                    let message = 'è¿æ¥å¤±è´¥'231232                    if (error.response) { // æå¡ç«¯ååº233                        const { status } = error.response234    235                        message = statusMsg[status] || error.message236    237                        const statusHandler = this.statusHandlers[status]238                        239                        toRawType.isFunction(statusHandler) && statusHandler()240241                    } else if (error.request) {242                        message = error.message243                    } else {244                        message = error.message245                    }246                   247                    // è°ç¨æç¤ºæ¹æ³248                    (this.isOpenTips && !disableTips) && this.tipsFunction(message)249    250                    // å䏿åºå¼å¸¸251                    return Promise.reject(message)252                }253254                // å±è½éè¯è¯·æ±çbaseURL项255                error.config.baseURL = null256257                // 设å®å·²éè¯æ¬¡æ°258                error.config.times = (error.config.times || 0) + 1259260                // éæ°å起请æ±261                return this.easyAxios(error.config)262            },263        )264    }265266    // éç¨267    REQUEST(method, url, param = {}, config = {}) {268        return new Promise((resolve, reject) => {269            this.easyAxios({270                method: method,271                url: url,272                [['get','delete'].includes(method.toLocaleLowerCase()) ? 'params' : 'data']: param,273                ...config274              })275            .then(response => resolve(response))276            .catch(error => error && reject(error)) // error 为 null æ¶ä¸ºåæ¶æçéå¤è¯·æ±è¿åçé误ï¼ä¸ç¨æç¤º277        })278    }279    280    // GET281    GET(url, param = {}, config = {}) {282        return this.REQUEST('get', url, param, config)283    }284    285    // POST286    POST(url, param = {}, config = {}) {287        return this.REQUEST('post', url, param, config)288    }289    290    // PUT291    PUT(url, param = {}, config = {}) {292        return this.REQUEST('put', url, param, config)293    }294    295    // DELETE296    DELETE(url, param = {}, config = {}) {297        return this.REQUEST('delete', url, param, config)298    }299    300    // FORMDATA301    FORMDATA(url, params, config = {}) {302        return this.REQUEST('post', url, dataToFormData(params), merge({303            headers: {304                'content-type': 'multipart/form-data;charset=UTF-8',305            },306        }, config))307    }308309    // æ·»å æ£å¨è¯·æ±ç310    addPendingRequest(config) {311        if (!this.isOpenCancelDuplicateRequest) return312313        // èµå¼æä¸æ¥å£æ¯å¦ç¦ç¨åæ¶éå¤è¯·æ±å设置 requestKey çé
ç½®314        const { easyAxiosConfig: { disableCancelDuplicate, requestKey } = {} } = config315316        if (!disableCancelDuplicate) {317318            const cncelDuplicateKey = toRawType.isUndefined(requestKey) ? [config.method, config.url, JSON.stringify(config.params), JSON.stringify(config.data)].join('&') : requestKey 319320            config.cancelToken = config.cancelToken || new axios.CancelToken(cancel => {321                if (cncelDuplicateKey && !this.PendingRequestMap.has(cncelDuplicateKey)) {322                    this.PendingRequestMap.set(cncelDuplicateKey, cancel)323                }324            })325        }326    }327328    // ç§»é¤æ£å¨è¯·æ±ç329    removePendingRequest(config) {330        if (!this.isOpenCancelDuplicateRequest) return331        332        // èµå¼æä¸æ¥å£æ¯å¦ç¦ç¨åæ¶éå¤è¯·æ±å设置 requestKey çé
ç½®333        const { easyAxiosConfig: { disableCancelDuplicate, requestKey } = {} } = config334335        if (!disableCancelDuplicate) {336            337            const cncelDuplicateKey = toRawType.isUndefined(requestKey) ? [config.method, config.url, JSON.stringify(config.params), JSON.stringify(config.data)].join('&') : requestKey 338339            if (cncelDuplicateKey && this.PendingRequestMap.has(cncelDuplicateKey)) {340                const cancel = this.PendingRequestMap.get(cncelDuplicateKey)341                cancel(cncelDuplicateKey)342                this.PendingRequestMap.delete(cncelDuplicateKey)343            }344        }345    }346347    // è·¯ç±åæ¢ï¼æ¸
餿æ PendingRequest ï¼å¨è·¯ç±è·³è½¬åè°ç¨348    clearPendingRequest() {349        for (const [cncelDuplicateKey, cancel] of this.PendingRequestMap) cancel(cncelDuplicateKey)350        this.PendingRequestMap.clear()351    }352353    // æ ¹æ®urlåparams对象è·åç¼å354    static getDataCache(method, url, params) {355        // çæ key356        const key = `${method}-${url}:${JSON.stringify(params)}`357        // è·å¾è¯·æ±å¯¹è±¡358        return OperationCache.get(key)359    }360361    // æ ¹æ®urlåparams对象设置ç¼å362    static setDataCache(method, url, params, data) {363        // çæ key364        const key = `${method}-${url}:${JSON.stringify(params)}`365        // 设置366        OperationCache.set(key, data, this.cacheEffectiveTime)367    }
...obj.js
Source:obj.js  
...3*/4const _toString = Object.prototype.toString;56function isObject(src) {7  return toRawType(src) === "Object";8}910// åºååºæ¬æ°æ®ç±»åååºç¨æ°æ®ç±»å11function isObjectType(src) {12  return src instanceof Object;13}1415// code from vue16function toRawType(value) {17  return _toString.call(value).slice(8, -1);18}1920function repeat(value, count, joinFlag) {21    const temp = []22    let i = 023    while(i < count) {24        temp.push(value)25        i ++26    }27    return joinFlag? temp.join(joinFlag): temp28}2930function keyStr2Arr(keyStr) {31    const arr = keyStr.split('.')32    const temp = arr.map(ele => {33        const matchArr = ele.match(/\[\d+\]/g)34        if(matchArr) {35            const okey = ele.substr(0, ele.indexOf(matchArr[0]))36            if(okey) return [okey].concat(matchArr.map(ma => parseInt(ma.slice(1, -1))))37            return matchArr.map(ma => parseInt(ma.slice(1, -1)))38        } else {39            return ele40        }41    })42    return temp.reduce((a, b) => {43        return a.concat(b)44    }, [])45}4647// æ ¹æ®keyarrçæä¸ä¸ªå¼ç¨å¯¹è±¡48function composeObject(keyarr, value, next) {49    let temp 50    const key = keyarr[next]51    if(typeof key === 'number') {52        if(next === keyarr.length - 1) {53            temp = [ ...repeat(undefined, key) , value]54        } else {55            temp = [...repeat(undefined, key), composeObject( keyarr, value, next + 1)]56        }57    } else if(typeof key === 'string') {58        if(next === keyarr.length - 1) {59            temp = {60                [key]: value61            }62        } else {63            temp = {64                [key]: composeObject( keyarr, value, next + 1)65            }66        }67    }68    return temp 69}7071// key/vlaue深穿,72function deepPierceByKey(origin, keystr, value) {73    const keys = keyStr2Arr(keystr)74    let temp = origin75    try {76        keys.forEach((ele, index) => {77            if(index === keys.length - 1) {78                temp[ele] = value79            } else {80                temp = temp[ele]81            }82        })83    } catch(err) {84        throw Error('key path is not correct')85    }86    return origin87}8889//   console.log(toRawType(null))9091// æ·±æ· ,å¦ææ¯æ°ç»åå,æ¶é´åå,nullåå, æ¹æ³Functionåå, å
¶ä»å¼ç¨å¯¹è±¡åå92function deepClone(origin) {93  let resdata;94  const rowType = toRawType(origin);95  const _isObjectType = isObjectType(origin);96  if (_isObjectType) {97    if (rowType === "Object") {98      const keys = Object.keys(origin);99      resdata = new Object();100      for (let i = 0; i < keys.length; i++) {101        resdata[keys[i]] = deepClone(origin[keys[i]]);102      }103    } else if (rowType === "Array") {104      resdata = origin.map((ele) => {105        return deepClone(ele);106      });107    } else if (rowType === "Date") {108      resdata = new Date(origin.getTime());109    } else if (rowType === "Function") {110      // æé111      resdata = origin;112    } else {113      // å
¶ä»å¼ç¨å¯¹è±¡æé114      resdata = origin;115    }116  } else {117    // åºæ¬æ°æ®ç±»åç´æ¥èµå¼118    resdata = origin;119  }120  return resdata;121}122123// æ·±assign, æ·è´å¯¹è±¡æ¹æ³,对象æ°ç»ä¸null,Date çå¼ç¨å¯¹è±¡124 function deepAssign(origin, src, isIncludeArray = false) {125  const clone = deepClone(origin);126  if(toRawType(src) === 'Object') {127    return deepPierce(clone, src, isIncludeArray);128  } else if (toRawType(src) === 'Array') {129      let temp = clone130    src.forEach(ele => {131        temp = deepPierce(temp, ele, isIncludeArray)132    })133    return temp134  } else {135      return origin136  }137}138139140// isPierceArrayObj 表示æ¯å¦åºç©¿æ°ç»å
çå¼ç¨å¯¹è±¡,å©ç¨åå¼ç¨å¯¹è±¡,ä¸å¼è¾æ°å¯¹è±¡,æµè¯éè¿141function deepPierce(origin, src, isPierceArrayObj = false) {142  if (isObject(origin)) {143    const ori_keys = Object.keys(origin);144    if (isObject(src)) {145      const src_keys = Object.keys(src);146      const len = src_keys.length;147      for (let i = 0; i < len; i++) {148        if (ori_keys.indexOf(src_keys[i]) > -1) {149          if (isObject(origin[src_keys[i]])) {150            deepPierce(origin[src_keys[i]], src[src_keys[i]], isPierceArrayObj);151          } else if(isPierceArrayObj && toRawType(origin[src_keys[i]]) === 'Array' && toRawType(src[src_keys[i]]) === 'Array') {152            origin[src_keys[i]] = deepPierce(origin[src_keys[i]], src[src_keys[i]], isPierceArrayObj);153          } 154          else {155            origin[src_keys[i]] = src[src_keys[i]];156          }157        } else {158          origin[src_keys[i]] = src[src_keys[i]];159        }160      }161    } else {162      origin = src;163    }164  } else if(toRawType(origin) === 'Array' && toRawType(src) === 'Array') {165      if(isPierceArrayObj) {166        const originLen = origin.length167        const srcLen = src.length168        if(originLen >= srcLen) {169            origin = origin.map((ele, index) => {170                if(isObject(src[index])){171                    if(isObject(ele)) {172                        return deepPierce(ele, src[index], isPierceArrayObj);173                    } else {174                        return src[index]175                    }176                } else if(src[index] !== undefined && src[index] !== null) {177                    return src[index]178                } else {179                    return ele180                }181            })182        } else {183            origin = origin.map((ele, index) => {184                const isObjOri = isObject(ele)185                const isObjSrc = isObject(src[index])186                if(isObjSrc) {187                    if(isObjOri) {188                        return deepPierce(ele, src[index], isPierceArrayObj);189                    } else {190                        return src[index]191                    }192                }  else if(src[index] !== undefined && src[index] !== null) {193                    return src[index]194                } else {195                    return ele196                }197            }).concat(src.slice(originLen))198        }199      } else {200            origin = src;201        }202  } else {203      origin = src204  }205  return origin;206}207208export const clone = deepClone209export const assign = deepAssign210export const compose = composeObject211export const pierce = deepPierceByKey212213214// return;215216// // å
è¯è¯asignæ¹æ³, è¿æ¯å¯¹è±¡æ·è´æ¹æ³,217// // é®é¢å¾å¤,218// function objAsign(obj1, obj2) {219//   return Object.assign({}, obj1, obj2);220// }221222223224// // test225// // æµè¯å
éæ¹æ³, å¼ç¨å¯¹è±¡å°å夿,é¡ºä¾¿å¤æåºæ¬æ°æ®ç±»å226// function objectTest(origin) {227//   const clone = deepClone(origin);228//   deepTest(origin, clone);229// }230231// function testStringifyParse(origin) {232//   const clone = JSON.parse(JSON.stringify(origin));233//   deepTest(origin, clone);234// }235236// function repeat(str, count) {237//     if (!count || toRawType(count) !== "Number") return str;238//     let temp = "";239//     let i = 0;240//     while (i < count) {241//       temp += str;242//       i++;243//     }244//     return temp;245//   }246// // æµè¯æ·±å
é247// function deepTest(origin, clone, step = 0) {248//   const _rowTypeOrigin = toRawType(origin);249//   const _rowTypeClone = toRawType(clone);250//   const _isObjectTypeOrigin = isObjectType(origin);251//   const _isObjectTypeClone = isObjectType(clone);252//   if (_isObjectTypeOrigin && _isObjectTypeClone) {253//     if (origin === clone) {254//       console.log(origin, clone, "object: origin = clone, å¼ç¨å°å没å");255//       return;256//     }257//     if (_rowTypeOrigin === "Array" && _rowTypeClone === "Array") {258//       const len = origin.length;259//       for (let i = 0; i < len; i++) {260//         deepTest(origin[i], clone[i]);261//       }262//       return;263//     } else if (_rowTypeOrigin === "Array" && _rowTypeClone !== "Array") {
...inspect.spec.js
Source:inspect.spec.js  
...29    expect(toType(undefined)).toEqual('undefined')30    expect(toType(null)).toEqual('object')31  })32  it('toRawType', async () => {33    expect(toRawType(123)).toEqual('Number')34    expect(toRawType('123')).toEqual('String')35    expect(toRawType(true)).toEqual('Boolean')36    expect(toRawType({})).toEqual('Object')37    expect(toRawType([])).toEqual('Array')38    expect(toRawType(/abc/)).toEqual('RegExp')39    expect(toRawType(() => {})).toEqual('Function')40    expect(toRawType(Date)).toEqual('Function')41    expect(toRawType(new Date())).toEqual('Date')42    expect(toRawType(undefined)).toEqual('Undefined')43    expect(toRawType(null)).toEqual('Null')44  })45  it('toRawTypeLC', async () => {46    expect(toRawTypeLC(123)).toEqual('number')47    expect(toRawTypeLC('123')).toEqual('string')48    expect(toRawTypeLC(true)).toEqual('boolean')49    expect(toRawTypeLC({})).toEqual('object')50    expect(toRawTypeLC([])).toEqual('array')51    expect(toRawTypeLC(/abc/)).toEqual('regexp')52    expect(toRawTypeLC(() => {})).toEqual('function')53    expect(toRawTypeLC(Date)).toEqual('function')54    expect(toRawTypeLC(new Date())).toEqual('date')55    expect(toRawTypeLC(undefined)).toEqual('undefined')56    expect(toRawTypeLC(null)).toEqual('null')57  })...inspect.js
Source:inspect.js  
...10var toType = function toType(val) {11  return _typeof(val);12};13exports.toType = toType;14var toRawType = function toRawType(val) {15  return Object.prototype.toString.call(val).slice(8, -1);16};17exports.toRawType = toRawType;18var toRawTypeLC = function toRawTypeLC(val) {19  return toRawType(val).toLowerCase();20};21exports.toRawTypeLC = toRawTypeLC;22var isUndefined = function isUndefined(val) {23  return val === undefined;24};25exports.isUndefined = isUndefined;26var isNull = function isNull(val) {27  return val === null;28};29exports.isNull = isNull;30var isFunction = function isFunction(val) {31  return toType(val) === 'function';32};33exports.isFunction = isFunction;34var isBoolean = function isBoolean(val) {35  return toType(val) === 'boolean';36};37exports.isBoolean = isBoolean;38var isString = function isString(val) {39  return toType(val) === 'string';40};41exports.isString = isString;42var isNumber = function isNumber(val) {43  return toType(val) === 'number';44};45exports.isNumber = isNumber;46var isPrimitive = function isPrimitive(val) {47  return isBoolean(val) || isString(val) || isNumber(val);48};49exports.isPrimitive = isPrimitive;50var isDate = function isDate(val) {51  return val instanceof Date;52};53exports.isDate = isDate;54var isRegExp = function isRegExp(val) {55  return toRawType(val) === 'RegExp';56};57exports.isRegExp = isRegExp;58var isPromise = function isPromise(val) {59  return !isUndefined(val) && !isNull(val) && isFunction(val.then) && isFunction(val.catch);60}; // Extra convenience named re-exports...is.js
Source:is.js  
1// å¤ææ°æ®ç±»å彿°2function toRawType(value) {3	return Object.prototype.toString.call(value).slice(8, -1)4}5/** å符串 ç±»å6 * @param {string} str7 * @returns {Boolean}8 */9export function _isString(str) {10	if (typeof str === 'string' || str instanceof String) {11		return true12	}13	return false14}15/** null ç±»å16 * @param {null} arg17 * @returns {Boolean}18 */19export function _isNull(arg) {20	return toRawType(arg) === 'Null'21}22/** undefined ç±»å23 * @param {undefined} arg24 * @returns {Boolean}25 */26export function _isUndefined(arg) {27	return arg === void 028}29/** boolean ç±»å30 * @param {boolean} arg31 * @returns {Boolean}32 */33export function _isBoolean(arg) {34	return toRawType(arg) === 'Boolean'35}36/** function ç±»å37 * @param {function} arg38 * @returns {Boolean}39 */40export function _isFunction(arg) {41	return toRawType(arg) === 'Function'42}43/** array ç±»å44 * @param {Array} arg45 * @returns {Boolean}46 */47export function _isArray(arg) {48	if (typeof Array.isArray === 'undefined') return toRawType(arg) === 'Array'49	return Array.isArray(arg)50}51/** object ç±»å52 * @param { object } arg53 * @returns {Boolean}54 */55export function _isObject(arg) {56	return toRawType(arg) === 'Object'57}58/** regExp ç±»å59 * @param { regExp } arg60 * @returns {Boolean}61 */62export function _isRegExp(arg) {63	return toRawType(arg) === 'RegExp'64}65/** symbol ç±»å66 * @param { symbol } arg67 * @returns {Boolean}68 */69export function _isSymbol(arg) {70	return toRawType(arg) === 'Symbol'71}72/** date ç±»å73 * @param { date } arg74 * @returns {Boolean}75 */76export function _isDate(arg) {77	return toRawType(arg) === 'Date'78}79/** 空对象 {},[],null,åå
¶å®éå¯¹è±¡æ°æ®80 * @param { obj } arg81 * @returns {Boolean}82 */83export function _isEmptyObject(arg) {84	for (const name in arg) {85		return false86	}87	return true...utils.js
Source:utils.js  
...13	'Boolean',14	'Function',15	'RegExp'16	].forEach((t) => {17		toRawType['is' + t] = (o) => toRawType(o) === t.toLocaleLowerCase()18	})19})()202122// å并对象ï¼ä¸¤ä¸ªå¯¹è±¡ç¸å屿§åçå¼å°æ·»å å¨ä¸èµ·23export const merge = (...objs) =>24  	[...objs].reduce(25		(acc, obj) =>26			Object.keys(obj).reduce((a, k) => {27				acc[k] = acc.hasOwnProperty(k) ? [].concat(acc[k]).concat(obj[k]) : obj[k]28				return acc29			}, {}30		), {}31	)
...lang.js
Source:lang.js  
2export function hasOwn(obj, key) {3  return hasOwnProperty.call(obj, key)4}5const _toString = Object.prototype.toString6export function toRawType(value) {7  return _toString.call(value).slice(8, -1)8}9export function isObject(value) {10  return value && typeof value === 'object'11}12export function isArray(value) {13  return toRawType(value) === 'Array'14}15export function isPlainObject(value) {16  return toRawType(value) === 'Object'17}18export function isFunction(value) {19  return toRawType(value) === 'Function'20}21export function isEmptyObject(value) {22  if (isPlainObject(value)) {23    return Object.keys(value).length === 024  }25  return false...specific-obj-type.js
Source:specific-obj-type.js  
1function toRawType(value) {2  let _toString = Object.prototype.toString;3  let str = _toString.call(value);4  return str.slice(8, -1);5}6console.log(toRawType(null));7// "Null"8console.log(toRawType(/sdfsd/));9//"RegExp"10console.log(toRawType([]));...Using AI Code Generation
1const { toRawType } = require('@playwright/test/lib/utils/utils');2console.log(toRawType({}));3console.log(toRawType([]));4console.log(toRawType(new Map()));5console.log(toRawType(new Set()));6console.log(toRawType(new Date()));7console.log(toRawType(new Error()));8Playwright is [BSD-2 licensed](Using AI Code Generation
1const { toRawType } = require('@playwright/test/lib/utils/utils');2const { toRawType } = require('@playwright/test/lib/utils/utils');3const { toRawType } = require('@playwright/test/lib/utils/utils');4const { toRawType } = require('@playwright/test/lib/utils/utils');5const { toRawType } = require('@playwright/test/lib/utils/utils');6const { toRawType } = require('@playwright/test/lib/utils/utils');7const { toRawType } = require('@playwright/test/lib/utils/utils');8const { toRawType } = require('@playwright/test/lib/utils/utils');9const { toRawType } = require('@playwright/test/lib/utils/utils');10const { toRawType } = require('@playwright/test/lib/utils/utils');11const { toRawType } = require('@playwright/test/lib/utils/utils');12const { toRawType } = require('@playwright/test/lib/utils/utils');Using AI Code Generation
1const { toRawType } = require('playwright/lib/utils/utils');2const assert = require('assert');3const { test, expect } = require('@playwright/test');4test('toRawType', async ({ page }) => {5  assert.equal(toRawType([]), 'Array');6  assert.equal(toRawType({}), 'Object');7  assert.equal(toRawType(new Map()), 'Map');8  assert.equal(toRawType(new Set()), 'Set');9  assert.equal(toRawType(new WeakMap()), 'WeakMap');10  assert.equal(toRawType(new WeakSet()), 'WeakSet');11  assert.equal(toRawType(new Int8Array()), 'Int8Array');12  assert.equal(toRawType(new Uint8Array()), 'Uint8Array');13  assert.equal(toRawType(new Uint8ClampedArray()), 'Uint8ClampedArray');14  assert.equal(toRawType(new Int16Array()), 'Int16Array');15  assert.equal(toRawType(new Uint16Array()), 'Uint16Array');16  assert.equal(toRawType(new Int32Array()), 'Int32Array');17  assert.equal(toRawType(new Uint32Array()), 'Uint32Array');18  assert.equal(toRawType(new Float32Array()), 'Float32Array');19  assert.equal(toRawType(new Float64Array()), 'Float64Array');20  assert.equal(toRawType(new ArrayBuffer()), 'ArrayBuffer');21  assert.equal(toRawType(new DataView(new ArrayBuffer())), 'DataView');22  assert.equal(toRawType(new Error()), 'Error');23  assert.equal(toRawType(new RegExp()), 'RegExp');24  assert.equal(toRawType(new Promise(() => {})), 'Promise');25  assert.equal(toRawType(async () => {}), 'AsyncFunction');26  assert.equal(toRawType(() => {}), 'Function');27  assert.equal(toRawType(function () {}), 'Function');28  assert.equal(toRawType(function* () {}), 'GeneratorFunction');29  assert.equal(toRawType(new Date()), 'Date');30  assert.equal(toRawType(new String()), 'String');31  assert.equal(toRawType(new Number()), 'Number');32  assert.equal(toRawType(new Boolean()), 'Boolean');33  assert.equal(toRawType(Symbol('')), 'Symbol');34  assert.equal(toRawType(new ArrayBuffer()), 'ArrayBuffer');35  assert.equal(toRawType(new SharedArrayBuffer()), 'SharedArrayBuffer');36  assert.equal(toRawType(new Blob()), 'Blob');37  assert.equal(toRawUsing AI Code Generation
1const { toRawType } = require('playwright-core/lib/server/common/utils');2console.log(toRawType({}))3console.log(toRawType([]))4console.log(toRawType(1))5console.log(toRawType('a'))6console.log(toRawType(true))7console.log(toRawType(new Date()))8console.log(toRawType(new Error()))9console.log(toRawType(new Map()))10console.log(toRawType(new Set()))11console.log(toRawType(new RegExp()))12console.log(toRawType(new WeakMap()))13console.log(toRawType(new WeakSet()))14console.log(toRawType(Symbol('a')))15console.log(toRawType(function(){}))16console.log(toRawType(null))17console.log(toRawType(undefined))18const { toRawType } = require('playwright-core/lib/server/common/utils');19console.log(toRawType({}))20console.log(toRawType([]))21console.log(toRawType(1))22console.log(toRawType('a'))23console.log(toRawType(true))24console.log(toRawType(new Date()))25console.log(toRawType(new Error()))26console.log(toRawType(new Map()))27console.log(toRawType(new Set()))28console.log(toRawType(new RegExp()))29console.log(toRawType(new WeakMap()))30console.log(toRawType(new WeakSet()))31console.log(toRawType(Symbol('a')))32console.log(toRawType(function(){}))33console.log(toRawType(null))34console.log(toRawType(undefined))35const { toRawType } = require('playwright-core/lib/server/common/utils');36console.log(toRawType({}))37console.log(toRawType([]))38console.log(toUsing AI Code Generation
1const { toRawType } = require('@playwright/test/lib/utils/utils');2describe('test', () => {3  it('test', async () => {4    console.log(toRawType('test'));5  });6});Using AI Code Generation
1const { toRawType } = require('playwright/lib/utils/utils');2const object = { a: 'b' };3console.log(toRawType(object));4const { toRawType } = require('playwright/lib/utils/utils');5const object = { a: 'b' };6console.log(toRawType(object));7toRawType(value)8const { toRawType } = require('playwright/lib/utils/utils');9const object = { a: 'b' };10console.log(toRawType(object));11const { toRawType } = require('playwright/lib/utils/utils');12const object = { a: 'b' };13console.log(toRawType(object));14const { toRawType } = require('playwright/lib/utils/utils');15const object = { a: 'b' };16console.log(toRawType(object));LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!
