preface

During this period of time, I reviewed the foundation of JS and combed my entire knowledge. The realization is not the optimal solution, welcome sisters to discuss and correct, we progress together.

Js based

Include: stabilization, throttling, closure, currying, new, bind, apply, call, this, scope, data type, common arrays & strings & regular methods, sort, deduplicate, beat flat arrays, Deep copy, cross-domain solutions, promise

  1. Image stabilization
function debounce_y(func, delay) {
  let timer = null;
  return function (. args) {
    timer && clearTimeout(timer);
    timer = setTimeout(() = > {
      func.apply(this, args);
    }, delay);
  };
}
Copy the code
  1. The throttle
function trottle_y(func, delay) {
  let start = new Date(a);let timer = null;
  return function (. args) {
    timer && clearTimeout(timer);
    if (new Date() - start >= delay) {
      func.apply(this, args);
      start = new Date(a); }else {
      timer = setTimeout(() = > {
        func.apply(this, args); }, delay); }}; }Copy the code
  1. closure
function count() {
  let count = 0;
  return function () {
    count++;
    console.log(count);
  };
}
Copy the code
  1. Currie,
function curry_y(func) {
  return function curried(. args) {
    if (args.length >= func.length) {
      func.apply(this, args);
    } else {
      return function (. args2) {
        curried.apply(this, args.concat(args2)); }; }}; }Copy the code
  1. New operator
function new_y(func) {
  let obj = {};
  obj.__proto__ = func.prototype;
  let res = func.apply(this);
  if (res instanceof Object) {
    return res;
  } else {
    returnobj; }}Copy the code
  1. Write a bind
/ / basic version
Function.prototype.bind_y = function (obj) {
  let that = this;
  return function (. args) {
    that.apply(obj, args);
  };
};
// Enhanced - Consider that bind can also pass more arguments as arguments to a function
Function.prototype.bind_y = function (obj, ... args0){
  let that = this;
  return function (. args){ that.apply(obj, args0.concat(args)); }}// Since bind may not pass target, it defaults to window
Function.prototype.bind_y = function (){
  let that = this; 
  let target = arguments[0];
  let args0 = Array.prototype.slice.call(arguments.1);
  return function (. args){ that.apply(target, args0.concat(args)); }}Copy the code
  1. Handwritten apply
// Use bind
Function.prototype.apply_y = function (obj) {
  return function (. args) {
    this.bind(obj)(args);
  };
};
// Do not use bind
Function.prototype.apply_y = function (target, args) {
  !target && (target = window);
  let fn = Symbol(a); target.fn =this; args ? target.fn(... args) : target.fn();delete target.fn;
};
Copy the code
  1. Write a call
Function.prototype.call_y = function (obj) {
  return function (. args) {
    this.bind(obj)(... args); }; };Copy the code
  1. this
// In normal functions, this refers to the object on which the function is called and is bound when called
var name = "y";
var cat = { name: "miao" };
function a() {
  console.log(this.name);
}
a(); // y
a.apply(cat); // miao

// In the arrow function, this inherits from the parent function and is bound when declared
var name = "y";
var cat = { name: "miao" };
var a = () = > {
  console.log(this.name);
};
a(); // y
a.apply(cat); // y
Copy the code
  1. scope
// Variable declaration is promoted
console.log(a); / / 1
console.log(b); // Uncaught ReferenceError: b is not defined
console.log(c); // Uncaught ReferenceError: c is not defined
var a = 1;
let b = 2;
const c = 3;

// The function declaration is promoted
console.log(y); {/ / ƒ (y). The console log (" nice to meet you!" )}
function y() {
  console.log("nice to meet you!");
}
Copy the code
  1. The basic data type is stored in the stack memory, and the reference type is stored in the heap memory, which can be understood from the access frequency.
  • Basic types Number, Boolean, String, Undefined, Null, BigInt, Symbol

  • Reference types Object, Array, Function, Date, and RegExp

The typeof method determines the basic type and function; The instanceof method determines the reference type; Object. The prototype. ToString. Call () method can accurately determine all data types.

  1. Common array & string & regular methods
// String method
"abc".split("");
"abc".indexOf("a");
"abc".charAt(0);
"abc".replace("a".1);
"abc".match("a");
"abc".matchAll("a");

// Array method
[1.2.3].join("");
[1.2.3].indexOf(1);
[1.2.3].findIndex((item) = > item > 1);
[(1.2.3] [0];
[1.2.3].reduce((acc, item, index, arr) = > {
  return acc + item;
});
[1.2.3].map((item, index) = > {});
[1.2.3].forEach((item, index) = > {});
[1[2.3]].flat(2);
[1.2.3].fill("a");
[1.2.3].includes(1);

// Regular method
/[a-z]/.test("abc");
/([a-z])(? ! \1)([a-z])/.exec("aac");
Copy the code
  1. The sorting
// sort
[1.3.5.2.4.6].sort((a, b) = > {
  return a - b;
});

// Quicksort
function quickSort(arr) {
  if (arr.length < 2) return arr;
  let left = [];
  let right = [];
  let flag = arr.splice(arr.length - 1.1) [0];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] > flag) {
      right.push(arr[i]);
    } else{ left.push(arr[i]); }}return quickSort(left).concat(flag, quickSort(right));
}

// Bubble sort
function bubbleSort(arr) {
  for (let i = 0; i < arr.length - 1; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if(arr[i] > arr[j]) { [arr[i], arr[j]] = [arr[j], arr[i]]; }}}return arr;
}

// Select sort
function selectSort(arr) {
  let min = 0;
  for (let i = 0; i < arr.length - 1; i++) {
    min = i;
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[j] < arr[min]) {
        min = j;
      }
    }
    [arr[i], arr[min]] = [arr[min], arr[i]];
  }
  return arr;
}
Copy the code
  1. duplicate removal
// new Set
new Set([1.2.1.2]);

/ / traverse
function uniq(arr) {
  for (let i = 0; i < arr.length - 1; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i] === arr[j]) {
        arr.splice(j, 1); i--; }}}return arr;
}
Copy the code
  1. Pat down array
// flat
[1[1[3.4]]].flat(3);

/ / recursion
function flat_y(arr) {
  let res = [];
  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      res = res.concat(flat_y(arr[i]));
    } else{ res.push(arr[i]); }}return res;
}
Copy the code
  1. Deep copy
function deepClone_y(obj, map = new Map(a)) {
  let type = Object.prototype.toString.call(obj);
  if(["[object String]"."[object Number]"."[object Undefined]"."object Boolean",
    ].includes(type)
  )
    return obj;
  if (type === "[object Array]") {
    if (map.get(obj)) return map.get(obj);
    let arr = [];
    map.set(obj, arr);
    for (let i = 0; i < obj.length; i++) {
      arr.push(deepClone_y(obj[i], map));
    }
    return arr;
  }
  if (type === "[object Object]") {
    if (map.get(obj)) return map.get(obj);
    let res = {};
    map.set(obj, res);
    for (let key in obj) {
      res[key] = deepClone_y(obj[key], map);
    }
    return res;
  }
  New Function(' argument ',' body ')
}
Copy the code
  1. Cross-domain solution If the port is the same, it is called same-origin
  • jsonp

Using script tags to achieve cross-domain PS: has been out of date why to test

  • webpack-dev-server proxy

proxy: {
    '/api': {
        target: 'http://127.0.0.1:7001/'.changeOrigin: true.pathRewrite: {
            '^/api': '/api'}}}Copy the code
  • cors
Access-Control-Allow-Origin: http://www.test.com
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: FooBar
Content-Type: text/html; charset=utf-8
Copy the code
  • The Node Server requests forwarding
  1. Write a promise
class promise_y{
    constructor(executor){
        this.status = 'pending';
        this.value = undefined;
        this.reason = undefined;
        this.successCallbacks = [];
        this.failCallbacks = [];
        let resolve = (data) = > {
            if(this.status === 'pending') {this.status = 'fullfilled';
                this.value = data;
                this.successCallbacks.forEach(func= >func()); }};let reject = (data) = > {
            if(this.status === 'pending') {this.status = 'rejected';
                this.reason = data;
                this.failCallbacks.forEach(func= >func()); }}try{
            executor(resolve,reject);
        }catch(e){ reject(e); }}then(onFullfilled, onRejected){
            if(this.status === 'fullfilled'){
                onFullfilled(this.value);
            }
            if(this.status === 'rejected'){
                onRejected(this.reason);
            }
            if(this.status === 'pending') {this.successCallbacks.push(() = > {
                    onFullfilled(this.value);
                });
                this.failCallbacks.push(() = > {
                    onRejected(this.reason)
                })
            }
    }
}
Copy the code

Knowledge is not perfect, can be used as a review catalogue, will continue to improve and update, welcome to like and concern ah. Code girl is not easy, but please don’t give up, because you are not alone in the fight, come on.