A, bind, call, apply function implementation

Changes this in the execution context of a Function, but does not execute the Function (the method on the prototype object of the Function constructor)

Function.prototype.myBind = function (target) { if (typeof this ! == 'function') { throw Error('myBind is not a function') } var that = this var args1 = [...arguments].slice(1) var func = function () { var args2 = [..arguments].slice(1) return that.apply(target || window, args1.concat(args2)) } return func } Function.prototype.myCall = function (context=window) { if (typeof this ! == 'function') { throw Error('myBind is not a function') } context.fn = this var args = [...arguments].slice(1) var result = context.fn(.. args) delete context.fn return result } Function.prototype.myApply = function (context=window) { if (typeof this ! == 'function') { throw Error('myApply is not a function') } context.fn = this var result if (argument[1]) { result = context.fn(... arguments[1]) } else { result = context.fn() } delete context.fn return result }Copy the code

Second, the implementation of deep copy method

function cloneDeep (target, map = new WeakMap()) { const mapTag = '[object Map]'; const setTag = '[object Set]'; const arrayTag = '[object Array]'; const objectTag = '[object Object]'; const argsTag = '[object Arguments]'; const boolTag = '[object Boolean]'; const dateTag = '[object Date]'; const numberTag = '[object Number]'; const stringTag = '[object String]'; const symbolTag = '[object Symbol]'; const errorTag = '[object Error]'; const regexpTag = '[object RegExp]'; const funcTag = '[object Function]'; const deepTag = [mapTag, setTag, arrayTag, objectTag, argsTag]; function isObject (target) { return typeof target === 'function' || typeof target === 'obejct'; } function getType (target) { return Object.prototype.toString.call(target); } if (! isObejct(target)) { return target; } function getInit (target) { return new (target.constructor) } function cloneOtherType (target, type) { } const type = getType(target); let cloneTarget; if (deepTag.includes(type)) { cloneTarget = getInit(target); } else { retrun cloneOtherType(target, type); } if (map.get(target)) { return map.get(target); } map.set(target, cloneTarget); if (type === setTag) { target.forEach(item => { cloneTarget.add(deepClone(item, map)); }) return cloneTarget; } if (type === mapTag) { target.forEach((key, value)=> { cloneTarget.set(key, deepClone(value, map)); }) return cloneTarget; } for (let key in target) { cloneTarget[key] = deepClone(target[key], map); } return cloneTarget; }Copy the code

Ideas:

  • Enter the target to be deep-copied and output the deep-copied result
  • Through the Object. The prototype. ToString accurate judgment of the incoming target, the data type of the target when the target data type for the Object or array, the recursive traversal of the target until when traversing all the data in an array or Object as the basic data types

Realization of array Flat function

Array.prototype.flat = function () {
    var temp = []
    function recurision (arr) {
        for (var i = 0; i < arr.length; i++) {
            let item = arr[i]
            if (Array.isArray(item)) {
                recurision(item)
            } else {
                temp.push(item)
            }
        }
    }
    recurision(this)
    return temp
}
Copy the code

Realization of n factorial

Analysis: first to find the law, for example, 3 factorial is equal to 3*2*1, which is equal to n*n-1*n-2 factorial, which is equal to 3*2*1 factorial, after the calculation to 1 factorial, the whole calculation process just ended. So it’s easy to think of recursively taking the factorial of this number, because one, there’s a pattern to the calculation, and two, it has an exit that eventually stops the calculation, that is, it stops when it reaches one, and then recursively does that

The function of the factorial (num) {if (num < 0) {throw new Error (' negative not factorial ')} the if (num = = = 1 | | num = = = 0) {1} return return num * factorial(num-1) } factorial(3) //6Copy the code

Fibonacci sequence is realized

Analysis: according to the factorial analysis process, not described here

Function Fibonacci (n) {if (n <= 1) {return 1}; return fibonacci(n - 1) + fibonacci(n - 2); }Copy the code

Implement a function that calculates the length of a string byte

Analysis: First of all, we need to know that the byte length of English is 1, while the byte length of Chinese is 2, but how to determine whether the current character bit is Chinese or English? CharCodeAt is used to determine whether the current character bit’s Unicode encoding is greater than 255, which is Chinese, then add 2 to the byte length of the string. If it is less than 255, the length of the string is incremented by 1

Function countBytesLength(STR){var length = 0; i < str.length; I ++) {if (STR [I].charcodeat (I) > 255) {length+ = 2} else {length++}} return length} var STR = 'DBCDouble ' countBytesLength(str) //11Copy the code

Implement isNaN functions

Analysis: To determine if the value passed in is “is not a number”(isNaN full), first perform an implicit conversion of the number, implement number (x) through the number wrapper class, and then determine if the value returned by Numberz(x) is a NaN, and if so, compare it to a NaN. However, NaN is of type number, but cannot be compared, so we first return the result of number (x) as a string, and then determine, implement as follows

function isNaN(num) {
    var ret = Number(num)
    ret += ''
    if (ret === 'NaN') {
        return true
    }
    return false
} 
isNaN('123abc') // true
Copy the code

Implement array push function

Array.prototype (); array.prototype (); array.prototype (); array.prototype (); array.prototype ()

Array.prototype.push = function () {
    for (var i = 0; i< arguments.length; i++) {
        this[this.length] = arguments[i]
    }
    return this.length
}
Copy the code

Implement typeOF that recognizes all data types

Typeof is a global method located on the window object, so we need to mount it on the Window object after defining it. Basic data types and complex data types (reference data type), we need through the Object. The prototype. The toString method to do the only why data types, the most accurate judgment about the current value implementation code below

window.typeof = function (value) {
  return Object.prototype.toString.call(val).slice(8, -1)
}
Copy the code

Eight, the realization of the array to the method

Analysis: First of all, because we are implementing a deduplication method for all array instances, we are also programming on the prototype chain

Array.prototype.unique = function () {var obj = {} var result = [] for (var I = 0; i < this.length; i++) { if (! Obj [this[I]]) {obj[this[I]] = true result.push(this[I])}} return result} var arr = [1,2,2,3,3] arr.unique() Array.prototype.unique = function () {array.prototype. includes var result = [] for (var I = 0; i < this.length; i++) { if (! Result.push (this[I])}} return result} array.prototype. Unique = function () {result.push(this[I])}} return result.push(this[I]) Var result = new Set(this) return array. from(result) return array. from(result) return array.prototype. unique = Array Array.prototype.filter () {array.prototype. filter () {array.prototype. filter () {array.prototype. indexOf (); Return this.filter((item, index) => this.indexof (item) === index)} return this.filter((item, index) => this.indexof (item) === index)}Copy the code

Nine, to achieve the function of shaking, throttling

function debounce (fn, wait=300) {
    var timer
    return function () {
        if (timer) {
            clearTimeOut(timer)
        }
        timer = setTimeout({
            fn.apply(this, arguments) 
        }, wait)
    }
}

function throttle (fn, wait=300) {
    var prev = +new Date()
    return function () {
       var now = +new Date()
       if (prev - now > 300) {
          fn.apply(this, arguments)
          prev = now
       }
    }
}
Copy the code

Encapsulate Ajax

/ / encapsulation method of ajax function ajax (options) {options = options | | {}; options.method = options.method || 'GET'; options.url = options.url || ''; options.async = options.async || true; options.data = options.data || null; options.success = options.success || function () {}; var xhr = null; if (XMLHttpRequest) { xhr = new XMLHttpRequest(); } else { xhr = new ActiveXObject('Microsoft.XMLHTTP'); } xhr.open(options.method, options.url, options.async) if (method === 'GET') { xhr.send(null); } else if (method === 'POST') { xhr.send(options.data); } xhr.onreadystatechange = function () { if (( (xhr.status >= 200 && xhr.status < 300) || xhr.status === 304 ) && xhr.readyState === 4) { options.success(xhr.responseText) } }}Copy the code

Implement the new operator

Function new (fn) {return function () {var obj = {'__proto__': function new (fn) {return function () {var obj = {'__proto__': fn.prototype } fn.apply(obj, arguments) return obj } }Copy the code

Twelve, commonly used six kinds of inheritance

1. Stereotype chain inheritance: A stereotype object of a subtype is an instance object of the parent type

function Person (name, age) {
    this.name = name 
    this.age = age
}

Person.prototype.setName = function () {
    console.log(this.name)
}

function Student (height) {
    this.height = height
}

Student.prototype = new Person()
var stu = new Student('175')
console.log(stu)
Copy the code

2, borrow constructor to implement inheritance: call the parent class constructor in the subclass constructor to implement inheritance

function Person (name, age) {
    this.name = name 
    this.age = age
}

Person.prototype.setName = function () {
    console.log(this.name)
}

function Student (height, age, name) {
    Person.call(this, age, name)
    this.height = height
}

var stu = new Student(175, 'cs', 24)
console.log(stu)
Copy the code

3. The combined inheritance method of prototype chain + borrowing constructor: inherits the attributes of the parent class and retains the advantages of passing parameters by calling the parent class constructor through call in the subclass constructor, and then realizes inheritance by taking the instance of the parent class as the prototype object of the subclass

function Person (name, age) { this.name = name this.age = age } function Son (sex, name, age) { Person.call(this, name, Prototype = new Person() var Son = new Son(' male ', 'DBCDouble', 25) console.log(Son)Copy the code

4. Parasitic combination inheritance (Holy Grail inheritance)

function Person (name, age) {
    this.name = name;
    this.age = age;
}

Person.prototype.setAge = function () {}

function Son (sex) {
    this.sex = sex;
}

function F () {}
F.prototype = Person.prototype
Son.prototype = new F()
Son.prototype.constructor = Son
var s1 = new Son()
console.log(s1)
Copy the code

Instanceof and Typeof implementations

Window.instanceof = instance window.typeof = typeof // Function instanceof (L, R) { var O = R.prototype L = L.__proto__ while (true) { if (L === null) { return false } if (L === O) { return true } L = l. __proto__}} function typeof () {/ / use the Object. The prototype. ToString implementation}Copy the code

JS Object-oriented pen test “Realize Cash”

1, implementation of Cash class, LazyMan

class Cash { constructor (value) { this.value = value } static add (... cashes) { return new Cash(cashes.reduce((result, item) => result += item, 0)) } add (... cashes) { return Cash.add(this, ... cashes) } valueOf () { return this.value } toString () { const tempArr = String(this.value).split('') const len = Tempar.length return tempar.map ((item, index) => item * math.pow (10, len-index-1)).join('-')}} You can call // LazyMan('Hank') as follows; Output: // Hi! This is Hank! // LazyMan('Hank').sleep(10).eat('dinner'); Output: // Hi! This is Hank! // // Wait 10 seconds.. // Wake up after 10s! // Eat dinner~ // LazyMan('Hank').eat('dinner').eat('supper'); // Hi This is Hank! // Eat dinner~ // Eat supper~ // LazyMan('Hank').sleepFirst(5).eat('supper'); Output: // // wait 5 seconds // Wake up after 5 // Hi This is Hank! // Eat supper~ // function lazyMan (name) { class _lazyMan (name) { constructor (name) { this.task = []; const fn = () => { console.log(`Hi This is ${ name }`) } this.task.push(fn); settimeout(() => { this.next(); }, 0) } next () { const fn = this.task.shift(); fn === 'function' && fn(); } eat (something) { const fn = () => { console.log(`Eat ${ something }`); this.next(); } this.task.push(fn); return this; } sleep (timeout) { const fn = () => { settmeout(() => { console.log(`Wake up after ${ timeout }`) this.next(); }, timeout * 1000) } this.task.push(fn); return this; } sleepFirst (timeout) { const fn = () => { settimeout(() => { console.log(`Wake up after ${ timeout }`); this.next(); }, timeout * 1000) } this.task.unshift(fn); return this; } } return new _lazyMan(name); }Copy the code

15. Handwritten observer mode, publish and subscribe mode

// Observer mode: The observed is directly related to the observer. When the observed state changes, all dependent observers are notified to adjust // with their own update method // publish and subscribe mode: Publishers and subscribers are not directly related. There is an Event channel between them that connects them. When the status of the publisher changes, only certain subscribers will be notified. Const Subject = (() => {const observers = []; const addOb = (... ob) => { observers.push(... ob) } const notify = () => { for (const ob of observers) { if (typeof fn === 'function') { ob.update(); }} return {addOb, notify}})() const ob1 = {update: () => console.log(' notify ob1')} const ob2 = {update: () => console.log(' notify ob2')} subject.addob (ob1, ob2); Subject.notify(); Const PubSub = (() => {const topics = {} const publish = (type,... args) => { for (const fn of topics[type]) { fn(... args); } } const subscribe = (type, fn) => { if (! topics[type]) { topics[type] = [] } topics[type].push(fn) } return { publish, subscribe } })(); PubSub.subscribe('SubA', () => console.log('Trigger subscribe SubA function')) PubSub,subscribe('SubB', () => console.log('Trigger subscribe SubB function')) PubSub.publish('SubA')Copy the code

Implement promises according to the PromiseA+ specification

Const resolvePromise = (promise2, x, resolve, reject) => {if (promise2 === x) {return TypeError(' cyclic reference ')); } if (x ! == null && (typeof x === 'object' || typeof x === 'function')) { try { let then = x.then; then.call(x, y => { resolvePromise(promise2, y, resolve, reject); }, err => { reject(err); }) } catch (err) { reject(err); } } else { resolve(x); } } class MyPromise { constructor (excutor) { this.status = 'pending'; this.value = undefined; this.reason = undefined; this.resolvedCallbacks = []; this.rejectedCallbacks = []; } const resolve = value => { this.status = 'fullfilled'; this.value = value; this.resolvedCallbacks.forEach(fn => fn()); } const reject = reason => { this.status = 'rejected'; this.reason = reason; this.rejectedCallbacks.forEach(fn => fn()); } try { excutor(resolve, reject); } catch (e) { reject(e); } then (onFullFilled, onRejected) { onFullFilled = typeof onFullFilled === 'function' ? onFullFilled : v => v; onRejected = typeof onRejected === 'function' ? onRejected : err => { throw err }; let promise2; if (this.status === 'fullfilled') { promise2 = new MyPromise((resolve, reject) => { settimeout(() => { try { const x = onFullFilled(this.value); resolvePromise(promise2, x, resolve, reject); } catch (err) { reject(err); } }) }) } else if (this.status === 'rejected') { promise2 = new MyPromise((resolve, reject) => { try { const x = onRejected(this.reason); resolvePromise(promise2, x, resolve, reject); } catch (err) { reject(err); } }) } else if (this.status === 'pending') { promise2 = new MyPromise((resolve, reject) => { this.onResolvedCallback.push(() => { settimeout(() => { try { const x = onFullFilled(this.value); resolvePromise(promise2, x, resolve, reject); } catch (err) { reject(err); } }, 0) }) this.onRejectedCallback.push(() => { settimeout(() => { try { const x = onRejected(this.reason); resolvePromise(promise2, x, resolve, reject); } catch (err) { reject(err); } }, 0) }) }) } return promise2; } catch (onRejected) { return this.then(null, onRejected); } static all (promises) { return new MyPromise(resolve => { const arr = []; let i = 0; const processData = (index, data) => { arr[index] = data; if (++i === promises.length) { resolve(arr); } } for (let i = 0; i < promises.length; i++) { promises[i].then(data => { processData(i, data); }) } }) } static race (promises) { return new MyPromise((resolve, reject) => { for (let i = 0; i < promises.length; i++) { promises[i].then(resolve, reject); } }) } static resolve (value) { return new myPromise(resolve => resolve(value)); } static reject (reason) { return new myPromise((resolve, reject) => reject(reason)); }}Copy the code

Implement the principle of Express middleware

//index.js node entry file const express = require('express'); const app = express(); const middleware1 = (req, res, next) => { console.log('middleware1 start'); next(); console.log('middleware1 end'); } const middleware2 = (req, res, next) => { console.log('middleware2 start'); next(); console.log('middleware2 end'); } const middleware3 = (req, res, next) => { console.log('middleware3 start'); next(); console.log('middleware3 end') } app.use(middleware1); app.use(middleware2); app.use(middleware3); // Express returns a function, app is a reference, and there is a use method. Const HTTP = require(' HTTP '); function express () { let middlewares = []; let i = 0; const app = (req, res) => { function next () { let task = middlewares[i++]; if (! task) return; task(req, res, next); } next(); } app.use = function (... newMiddlewares) { middlewares = [...middlewares, ...newMiddlewares]; } http.createServer(app).listen(3000, () => console.log('http server is running at 3000')) return app; } // Summary: The middleware is stored in an array in order, and each time the middleware is currently executed, the current middleware is given a call to the next middleware // to allow the caller to customize when to call the next middlewareCopy the code

React16 and React17 architectures are react-DOM implementations

The biggest difference between REact17 and React16 is that 16 implements depth-first traversal of virtual DOM objects by stack recursion. Stack recursion is uninterruptible and easy to run out of memory, which means that each time a status update occurs, a one-time stack recursion must be done from the root node to do depth-first traversal. When the CPU runs out of memory, unexpected updates may occur or updates may fail because browsers typically refresh at 60Hz, or 60 times a second. This means that each refresh is allocated 1000ms/60 = 16.6ms to complete JS script execution -> style layout -> style drawing. When the user triggers the click event or input box input (known as discrete event in React), the click event cannot be triggered or input box input cannot be focused, which makes the user feel sluggish. In react17, this shall not interrupt the update has been optimized, the single large not to interrupt the update task split into time slicing, namely tell a big update tasks down into smaller tasks, after complete a small task each time, can judge whether the current browser left remaining free time, and then make a decision whether to continue to the next task, In addition, the Scheduler module is added in the Act17 architecture to implement the update strategy based on priority, so that each update task can be tagged with the corresponding priority to do the update

// react16 react-dom.js function updateProps (node, props) {obect.keys (props).filter(p => p! == 'children').forEach(key => { if (key === 'className') { node.setAttribute('class', props[key]); } else { node.setAttribute(key, props[key]); } }) } function reconcileChildren (node, childVnode) { const newChildVnode = Array.isArray(childVnode) ? childVnode : [childVnode]; newChildVnode.forEach(child => render(child, node)); } function updateHostComponent (vnode) { const { type, props, children } = vnode; const node = document.createElement(type); updateProps(node, props); children && reconcileChildren(node, children); return node; } function updateFunctionComponent (vnode) { const { type, props } = vnode; const newVnode = type(props); const node = createNode(newVnode); return node; } function updateClassComponent (vnode) { const { type, props } = vnode; const newVnode = (new type(props)).render(); const node = createNode(newVnode); return node; } function updateTextNode (vnode) { const node = document.createTextNode(vnode); return node; } function createNode (vnode) { const { type, children } = vnode; if (typeof type === 'string') { node = updateHostComponent(vnode); } else if (typeof type === 'function') { node = type.prototype.isReactComponent ? updateClassComponent(vnode) : updateFunctionComponent(vnode); } else if (typeof vnode === 'string') { node = updateTextNode(vnode); } return node; } function render (vnode, container) { const node = createNode(vnode); container.appendChild(node); } export default {// react17 react-dom.js // let nextUnitOfWork = null; // Use let wipRoot = null for the react commit phase; function render (vnode, container) { wipRoot = { type: 'div', props: { children: { ... Vnode}}, child: null, sibling: null, return: null, stateNode: container} } function updateProps (ndoe, props) { Object.keys(props).forEach(key => { if (key === 'children') { node.textContent = props[key]; } else { if (key === 'className') { node.setAttribute('class', props[key]); } else { node.setAttribute(key, props[key]); } } }) } function createStateNode (workInProgress) { const { type, props } = workInProgress; const node = document.createElement(type); updateProps(node, props); return node; } function reconcileChildren (workInProgress, children) { if (typeof children === 'string' || typeof children === 'number') return; const newChildren = Array.isArray(children) ? children : [children]; let preFiber = null; newChildren.forEach((child, index) => { let newFiber = { type: child.type, props: child.props, stateNode: null, child: null, sibling: null, return: workInProgress }; if (index === 0) { workInProgress.child = newFiber; } else { preFiber.sibling = newFiber; } preFiber = newFiber; }) } function updateHostComponent (workInProgress) { if (! workInProgress.stateNode) { workInProgress.stateNode = createStateNode(workInProgress); } reconcileChildren(workInProgress, workInProgress.props.children); } function updateFunctionComponent (workInProgress) { const { type, props } = workInProgress; const children = type(props); reconcileChildren(workInProgress, children); } function performUnitOfWork (workInProgress) { const { type } = workInProgress; if (typeof type === 'string') { updateHostComponent(workInProgress); } else if (typeof type === 'function') { updateFunctionComponent(workInProgress); } if (workInProgress.child) { return workInProgress.child; } let nextFiber = workInProgress; while (nextFiber) { if (nextFiber.sibling) { return next.sibling; } else { nextFiber = nextFiber.return; } } } function commitWork (workInProgress) { if (! workInProgress) { return; } let parentFiber = workInProgress.return; while (! parentFiber) { parentFiber = parentFiber.return; } let parentNode = parentFiber.stateNode workInProgress.stateNode && parentNode.appendChild(workInProgress.stateNode); commitWork(workInProgress.child); commitWork(workInProgress.sibling); } function commitRoot () { commitWork(wipRoot.child); wipRoot = null; } function workLoop (IdleDeadLine) { while (nextUnitOfWork && IdleDeadLine.timeRemaining() > 1) { nextUnitOfWork = performUnitOfWork(nextUnitOfWork); } if (! nextUnitOfWork && wipRoot) { commitRoot(); }} / / here to simulate the React with requestIdleCallback scheduler Schedule window. RequestIdleCallback (workLoop) export default {render}Copy the code

Redux and React-redux

Funtion createStore (reducer) {if (enhancer) {return enhancer(createStore)(reducer); } let state = {}; const listeners = []; function subscribe (listener) { listeners.push(listener); } function dispatch (action) { state = reducer(state, action); listeners.forEach(listener => listener()); } function dispatch () { return state; } dispatch({ type: 'INIT_STATE' }) return { subscribe, getState, dispatch } } function combineReducers (reducers) { let finalReducers = {};  for (let key in reducers) { if (typeof reducers[key] === 'function') { finalReducers[key] = reducers[key]; } } return (state, action) => { const result = {}; for (var key in finalReducers) { const reducer = finalReducers[key]; const reducerState = reducer(state[key], action); result[key] = reducerState; } return result; } } function bindActionCreators (actionCreators, dispatch) { let result = {}; for (let key in actionCreators) { const actionCreator = actionCreators[key]; result[key] = (... args) => dispatch(actionCreator(... args)); } return result; } function applyMiddleware (... middlewares) { return createStore => (... args) => { const store = createStore(... args); const middlewareApi = { getState, dispatch: (... args) => dispatch(... args); } const chains = middlewares.map(middleware => middleware(middlewareApi)) dispatch = compose(... chains)(dispatch); return { ... store, dispatch } } } function compose (... funs) { if (funcs.length === 0) { return args => args; } if (funcs.length === 1) { return funs[0]; } return funcs.recduce((ret, item) => (... args) => ret(item(... args))); } // The react-redux API class Provider extends React.Component {constructor (props) {super(props); this.store = props.store; } static childContextType = { store: PropTypes.obejct } getChildContext () { return { store: this.store }; } return this.props.children; } const connect = (mapStateToProps, mapDispatchStateToProps) => WrapperComponent => { return class Connect extends React.Component { constructor (props, context) { super(props, context); this.store = context.store; this.state = { props: {} } } static contextType = { store: propTypes.obejct } componentWillMount () { this.store.subscribe(this.update); this.update(); } update () { const { getState, dispatch } = this.store; const stateToProps = mapStateToProps(getState()); const dispatchStateToProps = bindActionCreators(mapDispatchStateToProps, dispatch); this.setState({ props: { ... this.state.props, ... stateToProps, ... dispatchStateToProps } }) } render () { const { props } = this.state; return <WrapperComponent { ... props } /> } } }Copy the code

Implement simple WebPack packaging

//webpack.js const fs = require('fs'); const path = require('path'); const parser = require('@babel/parser'); const traverse = require('@babel/traverse').default; const babel = require('@babel/core'); function getModuleInfo (file) { const body = fs.readFileSync(file, 'utf-8'); const ast = parser.parse(body, { sourceType: 'module' }); const deps = {}; traverse(ast, { ImportDeclaration ({ node }) { const dirname = path.dirname(file); const absPath = './' + path.join(dirname, node.source.value); deps[node.source.value] = absPath; } }) const { code } = babel.transformFromAst(ast, null, { preset: ["@babel/preset-env"] }); const moduleInfo = { file, deps, code } return moduleInfo; } function parseModules (file) { const entry = getModuleInfo(file); cont temp = [entry]; const modules = {}; for (let i = 0; i < temp.length; i++) { const { deps } = temp[i]; if (deps) { for (let key in deps) { if (deps.hasOwnProperty(key)) { temp.push(getModuleInfo(deps[key])); } } } } temp.forEach(item => { modules[file] = `((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { eval("__webpack_require__.r(__webpack_exports__); \n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ }); \n/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils */ \"./src/utils.js\"); \n\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_utils__WEBPACK_IMPORTED_MODULE_0__.a + _utils__WEBPACK_IMPORTED_MODULE_0__.default); \n\n// __webpack_require__.r(__webpack_exports__); \n// __webpack_require__.d(__webpack_exports__, {\n// \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n// }); \n// var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(\"./src/utils.js\"); \n// const __WEBPACK_DEFAULT_EXPORT__ = (_utils__WEBPACK_IMPORTED_MODULE_0__.a + _utils__WEBPACK_IMPORTED_MODULE_0__.default); \n// console.log(_utils__WEBPACK_IMPORTED_MODULE_0__.default); \n// console.log(_utils__WEBPACK_IMPORTED_MODULE_0__.a); \n\n//# sourceURL=webpack://webpack5/./src/index.js?" ); /***/ }) })` }) } function bundle (file) { const modules = parseModules(files); return `(() => { "use strict" var __webapck_modules__ = modules; var __webpack_module_cache__ = {}; function __webpack_require__ (moduleId) { var cacheModule = __webpack_module_cache__[moduleid]; if (cacheModule ! == undefined) { return cacheModule.exports; } var module = __webpack_module_cache[moduleId] = { exports: {} } __webpack_modules__[moduleId](module, module.exports, __webpack_require__); return module.exports; } (() =>{ __webpack_require__.o = function () {} })(); (() => { __webpack_require__.d = function () {} })(); (() => { __webpack_require__.r = function () {} })() __webpack_require__(file); })()` } const content = bundle('./src/index.js'); fs.mkdirSync('dist'); fs.writeFileSync('./dist/bundle.js', content);Copy the code

12. I Promise

Var arr = [1,2,3] // use promise to print 1,2 every 1s, 3 function countDown (arr) { arr.reduce((p,x) => { return p.then(() => { return new Promise(reslove => setTimeout(() => console.log(x)), 1000)) }) }, Promise.resolve()); } // The red light is on 3s, yellow light is on 2s, green light is on 1s; How do I make three lights turn on alternately? Function red () {console.log('red'); function red () {console.log('red'); } function yellow () { console.log('yellow'); } function green () { console.log('green') } function light (cb, timeout) { return new Promise(resolve => { setTimeout({ cb(); resolve(); }, timeout); }) } function step () { Promise.resolve().then(() => { return light(red, 3000); }).then(() => { return light(yellow, 2000); }).then(() => { return light(green, 1000) }).then(() => { step(); }) } step(); // We know promise.all receives a Promise array to implement a concurrent request, but the request is unordered, //mergePromise function mergePromise (promises) {const result = [] return promises. Reduce ((p, x) => { return p.then(res => { result.push(res); return result; }) }, Promise.resolve()); Return Promise((resolve, reject) => {cons result = [];} return Promise((resolve, reject) => {cons result = []; let index = 0; for (let i = 0; i < promises.length; i++) { promises[i].then(res => { result[i] = res; if (++index === result.length) { resolve(result); // Promise() {return Promise() {return Promise() {return Promise(); reject) => { for (let i = 0; i< promises.length; i++) { promises[i].then(resolve, reject); Class {constructor (maxNum) {this.maxNum = maxNum; this.list = []; this.workingNum = 0; } addTask (... promises) { this.list.push(... promises); } start () { for (let i = 0; i < maxNum; i++) { this.doNext(); } } doNext () { if (this.list.length && this.workingNum < this.maxNum) { this.workingNum++; const promise = this.length.shift(); promise().then(() => { this.workingNum--; this.doNext(); })}}}Copy the code