If you have a dream, you must come to the big city, here can help you achieve your dream

Some dreams need the power of cities to achieve

The article will be updated continuously

1. Debounce and Throttle

function debounce(f, wait) { let timer; return (... args) => { clearTimeout(timer); timer = setTimeout(() => { f(... args); }, wait); } } function throttle(f, wait) { let timer; return (... args) => { if (timer) { return }; timer = setTimeout(() => { fn(... args); timer = null; }, wait); }}Copy the code

2. Implement the instanceof function manually

Core: Look up the prototype chain.

Function myInstanceOf(left, right) {return false if (typeof left! == 'object' || left === null) return false; // Let pro = object.getPrototypeof (left); // Let pro = object.getPrototypeof (left); While (true) {if (pro === null) return false; If (pro === right.prototype) return true; pro = Object.getPrototypeOf(pro); }}Copy the code

3. What is the difference between ===?

– Object fixes some special cases of errors based on strict equals, specifically +0 and -0, NaN and NaN. The source code is as follows:

Function is(x, y) {if (x === y) {if (x === y) {return x! == 0 || y ! == 0 || 1/x === 1/y; } else {//NaN===NaN is false, this is wrong, let's do an intercept here, x! == x, y == NaN, y == NaN == x && y ! == y } }Copy the code

4. Optimal combination inheritance —- Parasitic combination inheritance

function Parent() { this.name = 'parent'; This. Play = [1, 2, 3]; } function Child() { Parent.call(this); this.type = 'child'; } Child.prototype = Object.create(Parent.prototype); Child.prototype.constructor = Child;Copy the code

5. Simulate the map function

Array.prototype.map = function(callbackFn, ThisArg) {/ / an array type exception handling the if (this = = = null | | this = = = undefined) {throw new TypeError (" always read a property 'map' of null or undefined"); } / / callback type exception handling the if (Object. The prototype. ToString. Call (callbackFn)! = '[object Function]') { throw new TypeError(callbackfn + ' is not a function'); } // let O = Object(this); let T = thisArg; let len = O.length >>> 0; let A = new Array(len); for(let k=0; k < len; K++) {// remember in from the prototype chain section? If hasOwnProperty is a problem, it can only look for private properties. The important thing to note is that in is used to look for prototype chains. At the same time, if not found, not processed, can effectively handle the sparse array case. Considering similar to [,,,, 1,,,,,, 2,,,,, 3,,,,, 4] sparse array performance if in O (k) {let kValue = O [k]. Let mappedValue = callbackFn. Call (T, kValue, k, O); A[k] = mappedValue; } } return A; }Copy the code

6. Simulate the reduce function

Array.prototype.reduce = function(callbackFn, initialValue) { if (this === null || this === undefined) { throw new TypeError("Cannot read property 'reduce' of null or  undefined"); } if (Object.prototype.toString.call(callbackFn) ! = '[object Function]') { throw new TypeError(callbackfn + ' is not a function') } let O = Object(this); let len = O.length >>> 0; let k = 0; let accumulator = initialValue; if (accumulator === undefined) { for (; k<len; k++) { if (k in O) { accumulator = O[k]; k++; break; } } } if (k === len && accumulator === undefined) throw new Error('Each element of the array is empty'); for(; k<len; k++) { if (k in O) { accumulator = callbackFn.call(undefined, accumulator. O[k], k, O); } } return accumulator; }Copy the code

7. Implement push and POP methods

Array.prototype.push = function(... items) { let O = Object(this); let len = this.length >>> 0; let argCount = items.length >>> 0; if (len + argCount > 2 ** 53 - 1) { throw new TypeError("The number of array is over the max value restricted!" ) } for (let i = 0; i<argCount; i++) { O[len+1] = items[i]; } let newLength = len + argCount; O.length = newLength; return newLength; }Copy the code
Array.prototype.pop = function() {
   let O = Object(this);
   let len = this.length >>> 0;
   if (len === 0) {
       O.length = 0;
       return undefined;
   }
   len --;
   let value = O[len];
   delete O[len];
   O.length = len;
   return value;
}
Copy the code

8. Implement filter method

Array.prototype.filter = function(callbackfn, ThisArg) {/ / an array type exception handling the if (this = = = null | | this = = = undefined) {throw new TypeError (" always read a property of the filter null or undefined"); } / / callback type exception handling the if (Object. The prototype. ToString. Call (callbackfn)! = "[object Function]") { throw new TypeError(callbackfn + ' is not a function') } let O = Object(this); let len = O.length >>> 0; let resLen = 0; let res = []; for(let i = 0; i < len; i++) { if (i in O) { let element = O[i]; if (callbackfn.call(thisArg, O[i], i, O)) { res[resLen++] = element; } } } return res; }Copy the code

9. Simulate a new effect

function newOperator(ctor, ... args) { if (typeof ctor ! == 'function') { throw 'newOperator function the first param must be a function'; } let obj = Object.create(ctor.prototype); let res = ctor.call(obj, args); let isObject = typeOf res === 'object' && res ! == null; let isFunction = typeof res === 'function'; return isObject || isFunction ? res : obj; }Copy the code

10. Simulate a bind effect

Function.prototype.bind = function(content, ... Args) {// If (typeof this! == "function") { throw new Error("Function.prototype.bind - what is trying to be bound is not callable"); } var self = this; var fbound = function() { self.apply(this instanceof self ? this : content, args.concat(Array.prototype.slice.call(arguments))); } fbound.prototype = Object.create(self.prototype); return fbound; }Copy the code

Implement a call/apply function

Function.prototype.call = function (context, ... args) { let context = context || window; let fn = Symbol('fn'); context.fn = this; let result = context.fn(... args); delete context.fn; return result; }Copy the code
Function.prototype.apply = function (context, args) { let context = context || window; let fn = Symbol('fn'); context.fn = this; let result = context.fn(... args); delete context.fn; return result; }Copy the code

12. Manually implement shallow copy

const shallowClone = (target) => {
   if (typeof target === 'object' && target !== null) {
       const cloneTarget = Array.isArray(target) ? [] : {};
       for (let prop in target) {
           if (target.hasOwnProperty(prop)) {
               cloneTarget[prop] = target[prop];
           }
       }
       return cloneTarget;
   } else {
       return target;
   }
}
Copy the code

13. Implement deep copy manually

const isComplexDataType = obj => (typeof obj === 'object' || typeof obj === 'function') && (obj ! == null) const deepClone = function (obj, Hash = new WeakMap()) {if (constructor === Date) return new Date(obj) // Return a new Date object if (constructor ===) RegExp) return new RegExp(obj) if (hash. Has (obj)) return hash. Get (obj) let if (hash AllDesc = Object. GetOwnPropertyDescriptors (obj) / / traverse incoming parameters all the key features of the let cloneObj = Object. The create (Object. GetPrototypeOf (obj), AllDesc) // Inherit the stereotype chain hash. Set (obj, cloneObj) for (let key of Reflect.ownKeys(obj)) { cloneObj[key] = (isComplexDataType(obj[key]) && typeof obj[key] ! == 'function') ? deepClone(obj[key], hash) : obj[key] } return cloneObj }Copy the code

14. Implement the node callback mechanism

function EventEmitter() { this.events = new Map(); } const wrapCallback = (fn, once = false) => ({ callback: fn, once }) EventEmitter.prototype.addListener = function(type, fn, once = false) { let handler = this.events.get(type); if (! handler) { this.events.set(type, wrapCallback(fn, once)); } else if (handler && typeof handler.callback === 'function') { this.events.set(type, [handler, wrapCallback(fn, once)]); } else { handler.push(wrapCallback(fn, once)); } } EventEmitter.prototype.removeListener = function(type, listener) { let handler = this.events.get(type); if (! handler) return; if (! Array.isArray(handler)) { if (handler.callback === listener.callback) this.events.delete(type); else return; } for (let i=0; i<handler.length; i++) { let item = handler[i]; if (item.callback === listener.callback) { handler.splice(i, 1); i--; if (handler.length === 1) { this.events.set(type, handlerp[0]) } } } } EventEmitter.prototype.once = function(type, fn) { this.addListener(type, fn, true); } EventEmitter.prototype.emit = function(type, ... args) { let handler = this.events.get(type); if (! handler) return; if (Array.isArray(handler)) { handler.map((item) => { item.callback.apply(this, args); if (item.once) { this.removeListener(type, item) } }) } else { handler.callback.apply(this, args); this.removeListener(type, handler) } return true; } EventEmitter.prototype.removeAllListener = function(type) { let handler = this.events.get(type); if (! handler) return; else this.events.delete(type); }Copy the code

15. Write a promise

const PENDING = "pending"; const FULFILLED = "fulfilled"; const REJECTED = "rejected"; function MyPromise(executor) { let self = this; self.value = null; self.error = null; self.status = PENDING; self.onFulfilledCallbacks = []; self.onRejectedCallbacks = []; const resolve = (value) => { if (self.status ! == PENDING) return; setTimeout(() => { self.status = FULFILLED; self.value = value; self.onFulfilledCallbacks.forEach((callback) => callback(self.value)) }) } const reject = (error) => { if (self.status ! == PENDING) return; setTimeout(() => { self.status = REJECTED; self.error = error; self.onRejectedCallbacks.forEach((callback) => callback(self.error) }) } executor(resolve, reject); } MyPromise.prototype.then = function(onFulfilled, onRejected) { onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value; onRejected = typeof onRejected === 'function' ? onRejected : error => {throw error}; let bridgePromise; let self = this; if (this.status === PENDING) { return bridgePromise = new MyPromise((resolve,reject) => { self.onFulfilledCallbacks.push((value) => { try { let x = onFulfilled(value); resolvePromise(bridgePromise, x, resolve, reject); } catch (e) { reject(e); }}); self.onRejectedCallbacks.push((error) => { try { let x = onRejected(error); resolvePromise(bridgePromise, x, resolve, reject); } catch (e) { reject(e); } }) }) } else if (this.status === FULFILLED) { return bridgePromise = new MyPromise((resolve, reject) => { setTimeout(() => { try { let x = onFulfilled(self.value); resolvePromise(bridgePromise, x, resolve, reject); } catch (e) { reject(e); } }) }) } else { return bridgePromise = new MyPromise((resolve, reject) => { setTimeout(() => { try { let x = onRejected(self.error); resolvePromise(bridgePromise, x, resolve, reject); } catch (e) { reject(e); }})}); } } function resolvePromise(bridgePromise, x, resolve, reject) { if (x instanceof MyPromise) { if (x.status === PENDING) { x.then(y => { resolvePromise(bridgePromise, y, resolve,reject); }, error => { reject(error); }) } else { x.then(resolve, reject) } } else { resolve(x); } } MyPromise.prototype.catch = function(onRejected) { return this.then(null, onRejected); } MyPromise.resolve = (param) => { if (param instanceof MyPromise) return param; return new MyPromise((resolve, reject) => { if (param && param.then && param.then === 'function') { param.then(resolve, reject); } else { resolve(param); } }) } MyPromise.reject = (reason) => { return new Promise((resolve, reject) => { reject(reason); }) } MyPromise.prototype.finally = function(callback) { this.then(value => { return MyPromise.resolve(callback()).then(() => { return value; }) }, error => { return MyPromise.reject(callback()).then(() =>{ throw error; }) }) } MyPromise.all = function(promises) { return new Promise((resolve, reject) => { let result = []; let index = 0; let len = promises.length; if (len === 0) { resolve(result); return; } for(let i=0; i< len; i++) { MyPromise.resolve(promises[i]).then(data => { result[i] = data; index++; if (index === len) resolve(result); }).catch(err => { reject(err); }) } }) } MyPromise.race = function(promises) { return new MyPromise((resolve, reject) => { let len = promises.length; if (len === 0) { return; } for(let i=0; i< len; i++) { MyPromise.resolve(promises[i]).then(data => { resolve(data); return; }).catch(err => { reject(err); return; })}})}Copy the code

16. List reversal

class reverseList = function(head) { let pre = null; let cur = head; while(cur ! == null) { let next = cur.next; cur.next = pre; pre = cur; cur = next; } return pre; }Copy the code

17.Promise implements multi-image preloading

function preLoadImage(source){ let pr = []; source.foeEach(url => { let p = loadImage(url) }) Promise.all(pr) .then((images) => { console.log(images) }) } function loadImage(url) { return new Promise((resolve, reject) => { let img = new Image(); img.onload = () => resolve(img); img.onerror = reject; img.src = url; })}Copy the code

18. Perform the computed, Multiply, and add functions

    1. Computed (Multipy (NUM2), add(num3))(NUM1) // Equals num1 to num2 + Num3
    1. Computed (Add (num2), multiply(num3), add(num4))(num1) // Equals num1 + num2 to num3 + num4
const num1 = 1 const num2 = 2 const num3 = 3 const num4 = 4 let result = 0 function computed(... params) { if (! params) return function fn(value) { result = value params.forEach(item => { // console.log('item', item) // console.log('result', result) result += item }) // console.log('result2', result) return result } return fn } function add(value) { return value } function multiply(value) { return -value } console.log(computed(add(num2),multiply(num3),add(num4))(num1)) // 1 + 2 - 3 + 4Copy the code

19. Draw fan for CSS3

<div class="shanxing"> <div class="sx1"></div> <div class="sx2"></div> </div> .shanxing{ position: relative; width: 200px; height: 200px; border-radius: 100px; background-color: yellow; } .sx1{ position: absolute; width: 200px; height: 200px; transform: rotate(45deg); Clip: the rect (0100 px, 200 px, 0); border-radius: 100px; background-color: #fff; } .sx2{ position: absolute; width: 200px; height: 200px; transform: rotate(-45deg); Clip: the rect (0100 px, 200 px, 0); border-radius: 100px; background-color: #fff; }Copy the code