High-order function implementation AOP (Aspect oriented Programming)

What is aspect oriented programming?

Function.prototype.before = function (beforefn) { let _self = this; Return function () {// Proxy functions beforefn.apply(this, arguments); Return _self.apply(this, arguments); Function. Prototype. After = Function (afterfn) {let _self = this; return function () { let set = _self.apply(this, arguments); afterfn.apply(this, arguments); return set; } } let func = () => console.log('func'); func = func.before(() => { console.log('===before==='); }).after(() => { console.log('===after==='); }); func();Copy the code

Output result:

===before===
func
===after===   
Copy the code

Merge objects

const merge = (obj, target = {}) = > {
  Object.keys(obj).forEach(key= > {
    if (isObject(obj[key])) {
      if (isObject(target[key])) { // all are objects
        Object.keys(obj[key]).forEach(prop= > {
          target[key][prop] = obj[key][prop]
        })
      } else { // Target is not overridden directly
        if(target[key]) { target[key] = { [key]: target[key], ... obj[key] } }else {
          target[key] = obj[key]
        }
        
      }
    } else {
      if(isObject(target[key])) { target[key] = { ... target[key], [key]: obj[key] } }else {
        target[key] = obj[key]
      }
    }
  })
  return target
}
const obj1 = {
  "pid": 1."signup": "Registered"."menu": "Menu"."headers": {
    "common": "common"}}const obj2 = {
  "pid": 2."signup": {
    "sin": 2
  },
  "menu": {
    "id": 1
  },
  "headers": {
    "test": 123}}const result = merge(obj1, obj2)
/ / {
// pid: 2,
// signup: {signup: 'signup ', sin: 2},
// menu: {menu: 'menu ', id: 1},
// headers: { common: 'common', test: 123 }
// }
console.log(result)
Copy the code

factorial

const factorial1 = n= > {
  if (n <= 1) return 1
  return n * factorial1(n - 1)}// Tail recursive optimization
const factorial2 = (n, total = 1) = > {
  if (n <= 1) return total
  return factorial2(n - 1, total * n)
}

console.log(factorial1(3)) / / 6
console.log(factorial2(3)) / / 6
console.log(factorial1(5)) / / 120
console.log(factorial2(5)) / / 120
Copy the code

Binary search

// The loop invariant guess is equal to the middle position of L r
const bsearch = (A, x) = > {
  let l = 0
  let r = A.length - 1
  let guess
  while (l <= r) {
    console.log('find')
    guess = Math.floor((l + r) / 2)
    if (A[guess] === x) return guess
    if (A[guess] > x) r = guess - 1
    else l = guess + 1
  }
  return -1
}

let arr = [1.2.3.4.5.6.7.8]
console.log(bsearch(arr, 6)) / / 5
Copy the code

Turn a binary tree into a linked list

// Turn a tree structure into a linked list
class LinkNode {
  constructor(val) {
    this.val = val
    this.next = null}}// const flatten = function(root) {
// const head = new LinkNode(null)
// let linkNode = head
// const midOrder = (node) => {
// if (node == null) return
// linkNode.next = new LinkNode(node.val)
// linkNode = linkNode.next
// midOrder(node.left)
// midOrder(node.right)
/ /}
// midOrder(root)
// return head.next
// }

// Directly modify root
const flatten = function(root) {
  let head = new LinkNode(null)
  const linkHead = head
  const midOrder = (node) = > {
    if (node == null) return
    head.next = node
    head = node
    midOrder(node.left)
    midOrder(node.right)
    delete node.left
    delete node.right
  }
  midOrder(root)
  return linkHead.next
}
function TreeNode(val) {
  this.val = val
  this.left = this.right = null
}

const root = new TreeNode(1)
root.left = new TreeNode(2)
root.right = new TreeNode(5)

root.left.left = new TreeNode(3)
root.left.right = new TreeNode(4)
root.right.right = new TreeNode(6)
console.log(JSON.stringify(flatten(root), null.2))

/ / {
// "val": 1,
// "next": {
// "val": 2,
// "next": {
// "val": 3,
// "next": {
// "val": 4,
// "next": {
// "val": 5,
// "next": {
// "val": 6
/ /}
/ /}
/ /}
/ /}
/ /}
// }
Copy the code

Fibonacci numbers

The Fibonacci sequence starts with the third term, and each term is equal to the sum of the first two. Refers to a sequence of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144…

I’m going to figure out what the NTH term in the sequence points to

1. The recursion

function fib(n) { if (n === 1 || n === 2) return n - 1; return fib(n - 1) + fib(n - 2) } console.log(fib(10)); / / 34Copy the code

Time order 2 to the n.

2. Non-recursive

function fib(n) { let a = 0; let b = 1; let c = a + b; for (let i = 3; i < n; i++) { a = b; b = c; c = a + b; } return c; } console.log(fib(10)); / / 34Copy the code

Time is order n.

Implementation stack structure

const Stack = (() => { const wm = new WeakMap() class Stack { constructor() { wm.set(this, []) this.top = 0 } push(... nums) { let list = wm.get(this) nums.forEach(item => { list[this.top++] = item }) } pop() { let list = wm.get(this) let last = list[--this.top] list.length = this.top return last } peek() { let list = wm.get(this) return list[this.top - 1] } clear() { let list = wm.get(this) list.length = 0 } size() { return this.top } output() { return wm.get(this) } isEmpty() { return wm.get(this).length === 0 } } return Stack })() let s = new Stack() s.push(1, 2, 3, 4, 5) console.log(s.output()) // [ 1, 2, 3, 4, 5 ]Copy the code

Conversion of decimal to other bases

function binary(num, base = 2) {
  const stack = []
  const digits = '0123456789ABCDEF'
  while (num > base - 1) {
    stack.push(digits[num % base])
    num = ~~(num / 2)
  }
  stack.push(digits[num])
  return stack.reverse().join(' ')}console.log(binary(10)) / / '1010'
Copy the code

Conversion of decimal to other bases (using stacks)

function divideBy2(decNumber, base = 2) { let remStack = new Stack() let rem let binaryString = '' let digits = '0123456789ABCDEF' while (decNumber > 0) { rem = Math.floor(decNumber % base) remStack.push(rem) decNumber = Math.floor(decNumber / base) } while (! Remstack.isempty ()) {binaryString += digits[remstack.pop ()].toString()} return binaryString} // Convert decimal to other base let num =  100345 num.toString(2) // "11000011111111001" num.toString(8) // "303771" console.log(divideBy2(num, 2)) // "11000011111111001" console.log(divideBy2(num, 8)) // "303771"Copy the code

Array push = Array push = Array push

// class Array let obj = {'1': 'a', '2': 'b', length: 2, push: array.prototype.push}; // Array.prototype.push.call(obj, 'c'); obj.push('c') console.log(obj); // { '1': 'a', '2': 'c', length: 3 }Copy the code

Push and POP implementations

The underlying implementation of Array push relies on the Array’s Length property

Array.prototype.push2 = function(... rest){ this.splice(this.length, 0, ... rest) return this.length; }Copy the code

The same is true for POP

Array.prototype.pop2 = function(){
  return this.splice(this.length - 1, 1)[0];
}
Copy the code

Algorithm problem

1. Select num from an array where the sum of two items is num. If num exists, return the index position of the two items; otherwise false

function fn(num = 0, ary = []) { for (let i = 0; i < ary.length; i++) { let diff = num - ary[i]; let diffIndex = ary.indexOf(diff); if (diffIndex ! == -1 && diffIndex ! == i) { return [i, diffIndex]; } } return false; } let num = 3; let arr = [-1, 4, 6, 2]; console.log(fn(num, arr)); / / [0, 1]Copy the code

2. Merge two ordered arrays into a large sorted array

function mergeAry(left = [], right = []) { const result = []; while (left.length && right.length) { result.push(left[0] <= right[0] ? left.shift() : right.shift()); } return result.concat(left, right); } console.log(mergeAry([1, 2, 3], [1, 4, 8, 9])); // [1, 1, 2, 3, 4, 8, 9]Copy the code

Arr [x] + arr[y] = arr[z] return true if arr[x] + arr[y] = arr[z] return false otherwise

For example: [1, 18, 3, 2] => 1 + 2 = 3 => true; [3, 11, 2, 7] => false

let a1 = [2.99.3.5]
let a2 = [1.2.10.5]

function find(arr) {
  arr.sort((a, b) = > a - b)
  for (let i = 0; i < arr.length - 1; i++) {
    let cur = arr[i]
    for (let k = i + 1; k < arr.length; k++) {
      let next = arr[k]
      let diff = next - cur
      if(! [cur, next].includes(diff) && arr.includes(diff)) {return true}}}return false
}

console.log(find(a1)) // true
console.log(find(a2)) // false
Copy the code

Remove special characters and question marks, leaving only letters and single quotes. For special characters, if the question mark is followed by a letter, convert to uppercase “I’m? � � � driving �?? � to �? Beijing �? � � after � breakfast”

=> ‘I’m driving to Beijing after breakfast’

let str = "I'm? � � � driving �?? � to �? Beijing �? � � after � breakfast"

const reg1 = / � + \? ([a-z])/ig
const reg2 = /[^a-z']+/ig
str = str.replace(reg1, (a, g1) = > {
  return ' ' + g1.toUpperCase()
}).replace(reg2, ' ')
console.log(str) // 'I'm driving to Beijing after breakfast'
Copy the code

Template compilation

const template = ` 
      
{{ value }}
`
const data = { name: 'Brolly'.value: 'FE' } const compiler = (str, data) = > { const reg = / \ {\ {(. *?) \}\}/g return str.replace(reg, (patten, g1) = > { const key = g1.trim() return data[key] ? data[key] : ' '})}const content = compiler(template, data) // <div class="play" name="Brolly">FE</div> console.log(content) Copy the code

String repeat implementation

// native repeat 'ni'. Repeat (3); / / / / 'ninini' achieve a String. The prototype. RepeatString1 = function (n) {return Array (n + 1). The join (this); } console.log('ni'.repeatString1(3)); / / the second String. Prototype. RepeatString2 = function (n) {return Array (n.) the fill (this). The join ("); } console.log('ni'.repeatString2(3));Copy the code

The timer realizes the task scheduling period in days, 0-23 points, and is checked every hour

class Cron {
  constructor() {
    this.map = new Map(a)this.timer = null
    this.interval = 60 * 60 * 1000
    this._initCron()
    this._runCron()
  }
  addSub (time, fn) {
    if (this.map.has(time)) {
      this.map.get(time).push(fn)
    }
  }
  _run (time) {
    if (this.map.has(time)) {
      this.map.get(time).forEach(fn= > fn())
    }
  }
  _initCron() {
    for (let i = 0; i <= 23; i++) {
      this.map.set(i, [])
    }
  }
  resetCron () {
    for (let i = 0; i <= 23; i++) {
      this.map.set(0, [])
    }
  }
  _runCron () {
    this.timer = setInterval(() = > {
      const hour = (new Date()).getHours()
      this._run(hour)
    }, this.interval)
  }
  stopCron () {
    clearInterval(this.timer)
  }
  runCron () {
    this._runCron()
  }
}

const cron = new Cron()
cron.addSub(22.() = > {
  console.log('I want to eat.')
})
cron.addSub(22.() = > {
  console.log('I want to work')})Copy the code

Add three at a time to an array like 3,6,9…

const addThree = (start, target, arr = []) = > {
  if (start === target) {
    arr.push(start)
    return arr
  }
  if (start > target) {
    return arr
  }
  arr.push(start)
  return addThree(start += 3, target, arr)
}
console.log(addThree(3.40))
Copy the code

What happens when we create a new class

@param {function} new2(func) {// create an instance object o, Let o = object.create (func.prototype); // (this refers to the current instance in the constructor) let k = func.call(o); Return typeof k === 'object'? Return typeof k === 'object'? k : o; } function M() {this.name = 'liwenli'; } let m = new2(M); Log (M instanceof M); // instanceof check instance console.log(m instanceof Object); console.log(m.__proto__.constructor === M);Copy the code

this/bind

let obj = { a: 1}; function fn() { this.b = 100; return this.a; } let fe = fn.bind(obj); console.log(fe()); // this is obj console.log(obj); // { a: 1, b: 100 } console.log(new fe()); {b: 100}}Copy the code

Object. Create Compatible implementation

let obj1 = {id: 1}; Object._create = (o) => { let Fn = function() {}; // temporary constructor Fn. Prototype = o; return new Fn; } let obj2 = Object._create(obj1); console.log(obj2.__proto__ === obj1); // true console.log(obj2.id); // 1 // Native object. create let obj3 = object. create(obj1); console.log(obj3.__proto__ === obj1); // true console.log(obj3.id); / / 1Copy the code

An interview question

Method a

Function Man(name) {setTimeout(() => {// async: async: async: async: async: async: async console.log(`Hi! This is ${name}`); }, 0); } Man.prototype.sleep = function(time) { let curTime = new Date(); let delay = time * 1000; SetTimeout (() => {// async while (new Date() -curtime < delay) {} console.log(' Wake up after ${time} '); }, 0); return this; } Man.prototype.sleepFirst = function(time) { let curTime = new Date(); let delay = time * 1000; While (new Date() -curtime < delay) {} console.log(' Wake up after ${time} '); return this; } prototype = function(food) {setTimeout(() => {// async console.log(' eat ${food}~~ '); // async console.log(' eat ${food}~~ '); }, 0) return this; } return new Man(name); } // CodingMan('Peter'); // CodingMan('Peter').sleep(3).eat('dinner'); // CodingMan('Peter').eat('dinner').eat('supper'); // CodingMan('Peter').sleepFirst(5).eat('supper');Copy the code

Method 2

function CodingMan(name) { function fe() { fe.flag = true; console.log(`Hi! This is ${name}`); } fe.flag = false; fe.timer = setTimeout(() => { clearTimeout(fe.timer); if (! fe.flag) fe(); }, 0); return fe; } Function.prototype.sleep = function (delay) { this() this.await(delay); return this; } Function.prototype.sleepFirst = function (delay) { this.await(delay); this(); return this; } Function.prototype.eat = function (dinner) { setTimeout(() => { console.log(`Eat ${dinner}~`); }); return this; }; Function.prototype.await = function (delay) { delay = isNaN(delay) ? 0 : delay; let startTime = new Date(); let delayTime = delay * 1000; while (new Date() - startTime <= delayTime) { } console.log(`Wake up after ${delayTime}ms`); } // CodingMan('peter') // CodingMan('peter').sleep(2).eat('hanbao'); // CodingMan('peter').sleepFirst(2).eat('hanbao'); CodingMan('peter').eat('haha').eat('hanbao');Copy the code

A function called currying is used

The bind ke physical and chemical

  function add(a, b, c) {
    return a + b + c;
  }
  let f1 = add.bind(undefined, 100);
  console.log(f1(2, 3)); // 105 = 100 + 2 + 3
  let f2 = f1.bind(undefined, 200);
  console.log(f2(3)); // 303 = 100 + 200 + 3

Copy the code

Curry implementation (recursive call + valueOf)

Knowledge: When valueOf objects are implicitly converted to primitive data types in the browser environment (unary operator +object/ string concatenation ”+object), valueOf of itself is called. If a toString method exists, valueOf is called first and toString is called if valueOf returns a value that is not a basic data type, and toString returns a value that is not a basic data type.

ValueOf Call scenario

let obj = { x: 1, y: 2 }; obj.toString = function() { return this.x + this.y; } obj.valueOf = function() { return this.x + this.y + 100; } // In the following case itself valueOf is called console.log(" + obj); // 103 console.log(+obj); / / 103Copy the code
function fn() {};
fn.valueOf = () => console.log('valueof');
console.log(fn); // valueof
Copy the code
const mul = x => { const result = y => mul(x * y); // mul result.valueof = () => x; return result; } console.log(mul(2)(3)); Mul (x * y); // Mul (x * y); // Mul (x * y); // Mul (x * y); Return result result result = y => mul(2 *y); return result = y => mul(2 *y); // The second mul(2)(3) is equivalent to the result(3) returned by the first mul, Result => mul(2 *3) // mul(6) x = 6 // mul(6) x = 6 // mul(6) x = 6 // Log (mul(2)(3)) is equivalent to the last result returned by logCopy the code

Curry converts a multi-argument function to one that takes a single argument

function fe(a, b, c) { return a + b + c; } function curry(fe) { let args = []; // let len = args.length; return function bar() { args = [...args, ...arguments]; If (args. Length >= fe.length) {return fe.apply(this, args); } return bar; } } console.log(curry(fe)(1)(2)(3)); / / 6Copy the code

Evaluation of the currying part

Function (fn) {let args = []; return function fe() { if (arguments.length === 0) { return fn.apply(this, args); } [].push.apply(args, arguments); return fe; } } let count = currying(function (... rest) { return rest.reduce((prev, cur) => prev + cur, 0); }); console.log(count(100)(200)(10)()); / / 310Copy the code

The collection parameter is delayed for a specified number of times

Function fn(... rest) {console.log(rest); }; function after(fn, time = 1) { let params = []; return function(... rest) { params = [...params, ...rest]; if (--time === 0) { fn.apply(this, params); } } } let newFn = after(fn, 3); // Internal fn is executed three times before newFn(2) is executed; newFn(3); newFn(4);Copy the code

Function of the throttle

Throttle policy for elevators. Ensure that if the first person enters the elevator, it will be delivered on time 50 milliseconds later, without waiting. If no one is present, standby.

Let throttle = (fn, delay = 50) => {// Throttle control execution interval to prevent frequent triggering scroll resize mousemove let statTime = 0; return function (... args) { let curTime = new Date(); if (curTime - stattime >= delay) { fn.apply(this, args); stattime = curTime; }}}Copy the code

Regular effects must contain numeric and alphabetic case

  // Both alphanumeric and lowercase
  // let reg = /^(? ! ([a zA - Z] + | \ d +) $) [a zA - Z \ d] {8, 15} $/
  / / ^? ! ([0-9] + $)? ! [a-zA-Z]+$)[0-9A-Za-z]
  let reg = / ^ (? ! ([a zA - Z] + | [a-z \] d + |] [a-z \ d +) $) [a zA - Z \ d] {8, 15} $/
  console.log(reg.test('lolABC123')) // true
  console.log(reg.test('lol12313123')) // false
  console.log(reg.test('ADF12313123')) // false
  console.log(reg.test('12312313123')) // false
  console.log(reg.test('LLLLLLLLLL')) // false
  console.log(reg.test('aaaaaaass')) // fals
Copy the code

Function anti – shake complete version

/** * @desc * @param * @param immediate true * @param immediate true */ function debounce(func,wait,immediate) {var timeout; return function () { var context = this; var args = arguments; if (timeout) clearTimeout(timeout); if (immediate) { var callNow = ! timeout; timeout = setTimeout(function(){ timeout = null; }, wait) if (callNow) func.apply(context, args) } else { timeout = setTimeout(function(){ func.apply(context, args) }, wait); }}}Copy the code

shake

Debounce policy for elevators. If someone enters the elevator, wait 50 milliseconds. If someone else comes in, wait 50 milliseconds to reset the timer until 50 milliseconds times out and start shipping.

Let debounce = (fn, time = 50) => {// Anti-jitter control Idle time The user enters frequent let timer; return function (... args) { let that = this; clearTimeout(timer); timer = setTimeout(fn.bind(that, ... args), time); }}Copy the code

Deep copy compatible writing (not including stereotype attributes)

function deepCopy(obj) { if (typeof obj ! == 'object') return obj; if (typeof window ! Parse (json.stringify (obj)) == 'undefined' && window.JSON) {return JSON (json.stringify (obj)); } else { let newObj = obj.constructor === Array ? [] : {}; for(let key in obj) { newObj[key] = typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key]; } return newObj; } } let obj = {a: 1, b: [12]}; let newObj = deepCopy(obj); newObj.b[1] = 100; console.log(obj); console.log(newObj);Copy the code

Deep clone enhanced version

function cloneDeep(obj) {
  let type = isType(obj)
  if (type === 'Array' || type === 'Object') {
    return cloneObj(obj)
  } else if (type === 'Date') {
    return obj.constructor(obj)
  } else {
    return obj
  }
}

function cloneObj(obj) {
  let newObj = obj instanceof Array ? [] : {};
  for (let key in obj) {
    newObj[key] = typeof obj[key] === 'object' ? cloneObj(obj[key]) : obj[key]
  }
  return newObj;
}

function isType(o) {
  return /\[object\s(.*?)\]/.exec(Object.prototype.toString.call(o))[1]
}

let fn = function () {
  return 123
}
var a = [[1, 2, 3], [4, 5, 6, 7, fn]];
// let c = new Date();
// var b = cloneDeep(c);
var b = cloneDeep(a);
console.log(b[0], a[0]);
console.log(b[0] === a[0]);

Copy the code

Native data type detection easy encapsulation

Object.prototype.isType = function (type) { return function (params) { return Object.prototype.toString.call(params) ===  `[object ${type}]` } } let isString = Object.isType('String') let isArray = Object.isType('Array') console.log(isString(1)) // false console.log(isString('hello')) // true console.log(isArray(2)) // false console.log(isArray(['hello'])) // trueCopy the code

Array Reduce implementation

Array.prototype._reduce = function (callback, initVal) {
  let i = 0
  let result = initVal
  if (typeof initVal === 'undefined') {
    result = this[0]
    i++
  }

  for (i; i < this.length; i++) {
    result = callback(result, this[i])
  }
  return result
}

const arr = [1, 2, 3]
let result = arr._reduce((a, b) => {
  return a + b
}, 0)
console.log(result) // 6
Copy the code

The bind implementation of Function

1.es5 Function.prototype._bind = function(context) { let func = this; let params = [].slice.call(arguments, 1); let Fnop = function() {}; let fbound = function() { params = params.concat([].slice.call(arguments, 0)); return func.apply(this instanceof Fnop ? this : context, params); } Fnop.prototype = this.prototype; fbound.prototype = new Fnop(); return fbound; } function foo() { this.b = 100; return this.a; } let fe = foo._bind({ a: 1 }); console.log(fe()); // 1 console.log(new fe()); / / instance {b: 100} 2. Es6 Function. The prototype. Mybind = Function (context,... rest) { return (... params) => this.call(context, ... rest, ... params); }Copy the code

Function combination series compose (Reduce middleware)

// let fn1 = (a) => a + 1; let fn2 = (b) => b + 2; let fn3 = (c) => c + 3; let funs = [fn1, fn2, fn3]; let compose = (func) => { return arg => func.reduceRight((composed, fn) => fn(composed), arg); } console.log(compose(funs)(100)); Fn1 (fn2(fn3(100)))Copy the code

Redux source code for compose implementation (github.com/reduxjs/red…)

export default function compose(... funcs) { if (funcs.length === 0) { return arg => arg } if (funcs.length === 1) { return funcs[0] } return funcs.reduce((a, b) => (... args) => a(b(... args))) }Copy the code

Koa – compose

function compose(middleware) { return function(ctx, next) { let index = -1; return dispatch(0) function dispatch(i) { if(i <= index) return Promise.reject(new Error('next() called multiple times')); index = i; let fn = middleware[i] if (i === middleware.length) fn = next if (! fn) return Promise.resolve() try { return Promise.resolve(fn(ctx, dispatch.bind(null, i + 1))) } catch(e) { return Promise.reject(e) } } } } let mid1 = (ctx, next) => { console.log('ctx1', ctx); next() } let mid2 = (ctx, next) => { console.log('ctx2', ctx); next() } let mid3 = (ctx, next) => { console.log('ctx3', ctx); } let co = compose([mid1, mid2, mid3]) co('ctx')Copy the code

Co function

function *fn(a = 0) {
  console.log('a', a)
  const b = yield 2
  console.log('b', b)
  const c = yield Promise.resolve(3)
  console.log('c', c)
  return a + b + c
}

// const it = fn(1)
// it.next()
// it.next(2)
// it.next(3)
// co(fn, 1)

function fe() {
  return 100
}
run(fn, 10).then(res= > {
  console.log(res)
})

function run(gen) {
  const slice = [].slice
  const args = slice.call(arguments.1)
  return new Promise((resolve, reject) = > {
    const ite = (typeof gen === 'function') && gen.apply(this, args)
    if(! ite ||typeofite.next ! = ='function') return resolve(ite)
    function next(res) {
      const { value, done } = ite.next(res)
      if (done) {
        resolve(value)
      } else if (value instanceof Promise) {
        value.then(next)
      } else {
        next(value)
      }
    }
    next()
  })
}

Copy the code

Es6 Jane version of promise

class Promise {
 constructor(fn) {
   this.status = 'Pending'
   setTimeout(() => {
     fn((data) => {
       this.resolve(data)
     }, (error) => {
       this.reject(error)
     })
   })
 }
 
 resolve(data) {
   if (this.status === 'Pending') {
     this.success(data)
     this.status = 'Fulfilled'
   }
 }

 reject(error) {
   if (this.status === 'Pending') {
     this.error(error)
     this.status = 'Rejected'
   }
 }

 then(success, error) {
   this.success = success
   this.error = error
 }
}

let p1 = new Promise((resolve, reject) => {
 // reject('hello error');
 setTimeout(() => {
   resolve('hello promise')
 }, 1000)
})

p1.then((data) => console.log(data), (err) => console.log(err))

Copy the code

How do I proactively abort the Promise call chain

Const p1 = new Promise((resolve, reject) => {setTimeout(() => {// resolve('start')}, 1000); }); p1.then((result) => { console.log('a', result); Return promise.reject (' interrupt subsequent calls '); }). Then (result => {console.log('b', result);}). Then (result => {console.log('b', result); }).then(result => { console.log('c', result); }).catch(err => { console.log(err); }); // a start // interrupts subsequent callsCopy the code

Bluebird.promisify implementation (convert asynchronous callback API to promise form)

// promisify.js module.exports = { promisify(fn){ return function () { var args = Array.from(arguments); return new Promise(function (resolve, reject) { fn.apply(null, args.concat(function (err) { if (err) { reject(err); } else { resolve(arguments[1]) } })); }) } } } // main.js const fs = require('fs'); const {promisify} = require('./promisify.js'); const readFile = promisify('fs.readFile'); ReadFile ('./1.txt', 'utf8'). Then (data => {console.log(data); }).catch(err => { console.log(err); });Copy the code

Window. RequestAnimationFrame compatibility processing

window._requestAnimationFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback){ window.setTimeout(callback, 1000 / 60); }; }) ();Copy the code

Whether the string complies with palindrome rules

let str = 'My age is 0, 0 si ega ym.'; Function palindrome(params) {params = params.replace(/[\W\s_]/ig, "); function palindrome(params) {params = params.replace(/[\W\s_]/ig, "); return params.toLowerCase() === params.split('').reverse().join('').toLowerCase(); } console.log(palindrome(str)); Function palindrome(params) {params = params.replace(/[\W\s_]/ig, ").tolowerCase (); for (var i = 0, j = params.length-1; i<j; i++, j--) { if (params[i] ! == params[j]) { return false; } } return true; }Copy the code

deconstruction

/ / will destructuringArray ([1, 2, 3], 4], [c] a, [b], "") = > {2, a: 1, b: c: 4} const targetArray = [[2, 3] 1, 4]. const formater = "[a, [b], c]"; const destructuringArray = (values, keys) => { try { const obj = {}; if (typeof keys === 'string') { keys = JSON.parse(keys.replace(/\w+/g, '"$&"')); } const iterate = (values, keys) => keys.forEach((key, i) => { if(Array.isArray(key)) iterate(values[i], key) else obj[key] = values[i] }) iterate(values, keys) return obj; } catch (e) { console.error(e.message); }}Copy the code

Several ZuZhan flat

Flatten [[1, 2], 3, [[[4], 5]] into [1, 2, 3, 4, 5].

let arr = [[1, 2], 3, [[[4], 5]]]; Function flatten(arr) {return []. Concat (... arr.map(x => Array.isArray(x) ? flatten(x) : x) ) }Copy the code

Binary search

const arr = [1, 2, 3, 4, 5, 6, 7, 8]; Function binarySearch1(arr, dest, start = 0, end = data.length) { if (start > end) { return -1 } let midIndex = Math.floor((start + end) / 2); // let mid = arr[midIndex]; If (mid == dest) {return midIndex; If (dest < mid) {return binarySearch1(arr, dest, 0, midIndex - 1); Return binarySearch1(arr, dest, midIndex + 1, end); if (dest > mid) {return binarySearch1(arr, dest, midIndex + 1, end); } return -1; Return -1} console.log(binarySearch1(arr, 7, 3, 6)); Function binarySearch2(arr, dest) {let Max = arr.length-1; let min = 0; while (min <= max) { let mid = Math.floor((max + min) / 2); If (dest < arr[mid]) {if (dest < arr[mid]) {if (dest < arr[mid]) {if (dest < arr[mid]) { If (dest > arr[mid]) {if (dest > arr[mid]) {if (dest > arr[mid]) {if (dest > arr[mid]) {if (dest > arr[mid]); } else { return mid; } } return -1; 1} console.log(binarySearch2(arr, 3)); / / 2Copy the code

Binary search problem

In a two-dimensional array, each row is incremented from left to right and each column is incremented from top to bottom. Complete a function by entering the two-dimensional array and an integer to determine whether the integer is in the array

The idea is the same, but instead of going from one dimension to two, we can traverse the idea like this:

  • Pick the last one in the first row and judge (this is the largest one in the first row)
  • If the target is greater than that, increment the number of rows and iterate over the second row (because each column is incrementing)
  • If the target is less than that value, look it up in this line

Repeat the above steps

function findTarget(arr,target) { let i = 0; // let j = arr[I]. Length -1; While (I < arr. Length &&j >=0) {if(target < arr[I][j]) {j--; } else if (target > arr[i][j]) { i++; } else {return ` found, position in the ${I}, ${j} `}} return ` (${I}, ${j}) `} let arr = [[1, 2, 3, 4], [5,9,10,11], [13,20,21,23]] / / testCopy the code

Find duplicate elements in the array

Let arr = [1, 2, 4, 4, 3, 3, 1, 5, 3]; let arr = [1, 2, 4, 4, 3, 3, 1, 5, 3]; Function repeat1(arr){var result = [], map = {}; arr.map(function(num){ if(map[num] === 1) result.push(num); / / appeared before a is equal to 1 The repeated map (num) = (map (num) | | 0) + 1; });});}); return result; } console.log(repeat1(arr)); Function repeat(arr) {let result = arr. Filter ((x, I,); self) => { return self.indexOf(x) === i && self.lastIndexOf(x) ! == i }); // return result; } console.log(repeat(arr));Copy the code

Sort by the number of repetitions of the number in the array

[1, 2, 1, 2, 1, 3, 4, 5, 4, 5, 5, 2, 2] => [3, 4, 4, 5, 5, 5, 5, 2, 2] 1, 1, 1, 5, 5, 5, 2, 2, 2, 2] const repeatTimeSort = arr => { arr.sort((a, b) => a - b) let ary = [] while (arr.length > 0) { let a = arr[0] let start = arr.indexOf(a) let end = arr.lastIndexOf(a) + 1 ary.push(arr.splice(start, end - start)) } ary.sort((a, b) => a.length - b.length) return ary.reduce((prev, cur) => prev.concat(cur), []) } // [ 12, 13, 13, 11, 11, 11 ] console.log(repeatTimeSort([11, 12, 13, 11, 11, 13])) // [ 3, 4, 4, 1, 1, 1, 5, 5, 5, 2, 2, 2, 2 ] console.log(repeatTimeSort([1, 2, 1, 2, 1, 3, 4, 5, 4, 5, 5, 2, 2]))Copy the code

Without looping, create an array of length 100 with each element’s value equal to its subscript.

Function createArray(len, arr = []) {if (len > 0) {arr[--len] = len; createArray(len, arr); } return arr; } console.log(createArray(100)); Array(100).fill().map((_, I)=> I +1); [...Array(100).keys()]Copy the code

Convert an array to an associative structure tree

const roles = [
  { id: 1.name: 'a'.parentId: 0},
  { id: 2.name: 'b'.parentId: 0},
  { id: 3.name: 'c'.parentId: 1},
  { id: 4.name: 'd'.parentId: 1},
  { id: 5.name: 'e'.parentId: 2},
  { id: 6.name: 'f'.parentId: 2}]// const output = [{
// id: 1,
// name: 'a',
// parentId: 0,
// children: [
// { id: 3, name: 'c', parentId: 1, children: [] },
// { id: 4, name: 'd', parentId: 1, children: [] }
/ /]
/ /},
/ / {
// id: 2,
// name: 'b',
// parentId: 0,
// children: [
// { id: 5, name: 'e', parentId: 2 },
// { id: 6, name: 'f', parentId: 2 }
/ /]
/ /}
// ]


function convert(roles) {
  const root = []
  const dict = {}
  roles.forEach(item= > {
    if (item.parentId === 0) {
      root.push(item)
    }
    item.children = []
    dict[item.id] = item
  })
  
  roles.forEach(item= > {
    if(item.parentId ! = =0) {
      dict[item.parentId].children.push(item)
    }
  })
  return root
}

console.log(convert(roles))
Copy the code

JSON Flat data to tree structure JSON (JSON -> tree, tree -> JSON)

const json = [{
  id: 1.name: '1'.parentId: 0
}, {
  id: 3.name: '3'.parentId: 0
}, {
  id: 11.name: '11'.parentId: 1
}, {
  id: 12.name: '12'.parentId: 1
}, {
  id: 13.name: '13'.parentId: 1
}, {
  id: 111.name: '111'.parentId: 11
}, {
  id: 112.name: '112'.parentId: 2
}, {
  id: 21.name: '21'.parentId: 2
}, {
  id: 211.name: '211'.parentId: 21
}, {
  id: 1111.name: '1111'.parentId: 111
}, {
  id: 2.name: '2'.parentId: 0
}]

// json -> tree json Converts flat data to tree data
const jsonToTree = (jsonData, option) = > {
  const _defaultOption = {
    id: 'id'.pid: 'pid'.children: 'children'.rid: 0
  }

  const {
    id,
    pid,
    children,
    rid
  } = Object.assign({}, _defaultOption, option)

  const map = {}
  const tree = []
  jsonData.reduce((map, item) = > {
    map[item[id]] = item
    if (item[pid] === rid) {
      tree.push(item)
    }
    return map
  }, map)
  json.forEach(item= > {
    if (map[item[pid]]) {
      (map[item[pid]][children] || (map[item[pid]][children] = [])).push(item)
    }
  })
  return tree
}
const treeData = jsonToTree(json, {
  id: 'id'.pid: 'parentId'.children: 'children'
})
// console.log('tree', JSON.stringify(treeData, null, 2))

// tree -> json tree structure converts to JSON flat data
const treeToJson = (tree, option) = > {
  const _defaultOption = {
    pid: 'pid'.children: 'children',}const {
    children
  } = Object.assign(_defaultOption, option)

  const json = []
  const map = (data) = > {
    const queue = []
    data.forEach(item= > {
      queue.push(item)
    })
    while (queue.length) {
      const item = queue.shift()
      const children = item.children
      item.children = null
      deleteitem.children json.push({ ... item })if (children) {
        children.forEach(child= > queue.push(child))
      }
    }
  }
  map(tree)
  console.log('json', json)
}
treeToJson(treeData, {
  pid: 'parent'.children: 'kids'
})

Copy the code

Find the id of the object based on the keyword

var docs = [ { id: 1, words: ['hello', "world"] }, { id: 2, words: ['hello', "hihi"] }, { id: 3, words: ['haha', "hello"] }, { id: 4, words: ['world', "nihao"] } ]; FindDocList (docs, ['hello']) Id1 function findDocList(docs, word = []) {if (word. Constructor! == Array) return; let ids = []; for (let i = 0; i < docs.length; i++) { let {id, words} = docs[i]; let flag = word.every((item) => { return words.indexOf(item) > -1; }); flag && ids.push(id); } return ids; } findDocList(docs, ['hello', 'world']);Copy the code

The whole arrangement

const permute = function(nums) {
  if (nums.length <= 1) return [nums]

  const permutes = []
  for (let i = 0; i < nums.length; i++) {
    const num = nums[i]
    const others = nums.slice(0, i).concat(nums.slice(i + 1))
    const list = permute(others)
    list.forEach(item= > {
      permutes.push([num].concat(item))
    })
  }
  return permutes
};
const arr = [1.2.3]
console.log(permute(arr))
Copy the code

GetElementsByClassName is compatible

  function getByClass(cName) {
      if ('getElementsByClassName' in this) {
          return this.getElementsByClassName(cName);
      }
      cName = cName.replace(/(^\s+|\s+$)/g, '').split(/\s+/g);
      let eles = this.getElementsByTagName('*');
     for (let i = 0; i < cName.length; i++) {
        let reg = new RegExp(`(^| )${cName[i]}( |$)`);
        let temp = [];
        for (let j = 0; j < eles.length; j++) {
            let cur = eles[j];
            let {className} = cur;
            if (reg.test(className)) {
                temp.push(cur);
            }
        }
        eles = temp;
     }
     return eles;
  }
  console.log(content.getByClass('c1 c2 '));
Copy the code

Insertion sort

Insert sort compares from back to back until it hits a previous item that is smaller than the current item and inserts it after the previous item

function insertSort(arr) { let len = arr.length; let preIndex, current; for (let i = 1; i < len; i++) { preIndex = i - 1; current = arr[i]; While (preIndex >= 0 && arr[preIndex] > current) {arr[preIndex + 1] = arr[preIndex]; } arr[preIndex + 1] = current;} arr[preIndex + 1] = current; // If the previous item is less than the current item, the loop ends and the current item comes after the previous item} return arr; }Copy the code
function insert(arr, i, x) {
  let prev = i - 1;
  while(prev >= 0 && arr[prev] > x) {
    arr[prev + 1] = arr[prev];
    prev--;
  }
  arr[prev + 1] = x;
}

function insert_sort(arr) {
  for (let i = 1; i < arr.length; i++) {
    insert(arr, i, arr[i]);
  }
  return arr;
}

console.log(insert_sort([1, 10, 3, 0]));
Copy the code

Selection sort

Select sort each time you compare the current item to the next item to get the lowest index position and then swap the lowest and the current item

function selectSort(arr) { let len = arr.length; let temp = null; let minIndex = null; for (let i = 0; i < len - 1; I ++) {// compare minIndex = I; For (let j = I + 1; j < len; If (arr[j] < arr[minIndex]) {if (arr[j] < arr[minIndex]) {if (arr[j] < arr[minIndex]); }} // If (I! == minIndex) { temp = arr[i] arr[i] = arr[minIndex]; arr[minIndex] = temp; } } return arr; }Copy the code

Bubble sort

Bubble sort compares two adjacent terms and switches if the current value is greater than the latter

The bubbling 1

function swap(arr, i, j) { [arr[i], arr[j]] = [arr[j], arr[i]] } function bubleSort(arr) { let length = arr.length; let temp = null; for (let i = 0; i < length - 1; I++) {// let flag = false; For (let l = 0; l < length - i - 1; L++) {/ / control times if comparing each round (arr [l] > arr [m + 1]) {/ / temp = arr [l]; // arr[l] = arr[l + 1]; // arr[l + 1] = temp; swap(arr, l, l + 1); flag = true; }} If (! // if flag is still false after a round of comparison from start to end, it indicates that the order is sorted and there is no need to continue. return arr; } } return arr; }Copy the code

The bubbling 2

function swap(arr, i, j) {
  [arr[i], arr[j]] = [arr[j], arr[i]]
}

function bubble_sort(arr) {
  for (let i = arr.length - 1; i >= 1; i--) {
    for (let j = 1; j <= i; j++) {
      arr[j - 1] > arr[j] && swap(arr, j - 1, j)
    }
  }
  return arr;
}

console.log(bubble_sort([1, 10, 3, 0]));
Copy the code

Quicksort (Ruan Yifeng edition)

function quickSort(arr) {
    if (arr.length <= 1) return arr;
    let midIndex = Math.floor(arr.length / 2);
    let midNum = arr.splice(midIndex, 1)[0];
    let left = [];
    let right = [];
    for(let i = 0; i < arr.length; i++) {
        let cur = arr[i];
        if (cur <= midNum) {
            left.push(cur);
        } else {
            right.push(cur);
        }
    }
    return quickSort(left).concat(midNum, quickSort(right));
}

let arr = [2, 4, 12, 9, 22, 10, 18, 6];
quickSort(arr);
Copy the code

Quicksort second edition

let array = [9, 6, 20, 3, 2]; // let array = [15, 13, 20, 21, 29]; function quickSort(arr, left = 0, right = arr.length - 1) { let len = arr.length; let partitionIndex; // left = typeof left ! = 'number' ? 0 : left; // right = typeof right ! = 'number' ? len - 1 : right; if (left < right) { partitionIndex = partition(arr, left, right); quickSort(arr, left, partitionIndex - 1); quickSort(arr, partitionIndex + 1, right); } return arr; } function partition(arr, left, right) { let pivot = left; let index = pivot + 1; for (let i = index; i <= right; i++) { if (arr[i] < arr[pivot]) { swap(arr, i, index); index++; } } swap(arr, pivot, index - 1); return index - 1; } function swap(arr, i, index) { [arr[i], arr[index]] = [arr[index], arr[i]]; } console.log(quickSort(array));Copy the code

Merge sort

let array = [5, 13, 20, 3, 2]; // let array = [15, 13, 20, 21, 29]; function mergeSort(array) { let arr = array.slice(0); let len = arr.length; if (len < 2) { return arr; } let midIndex = Math.floor(len / 2); let left = arr.slice(0, midIndex); let right = arr.slice(midIndex); return merge(mergeSort(left), mergeSort(right)); } function merge(left, right) { let result = []; while(left.length && right.length) { result.push(left[0] < right[0] ? left.shift() : right.shift()); } if (left.length && ! right.length) { result = result.concat(left); } if (right.length && ! left.length) { result = result.concat(right); } return result; } console.log(mergeSort(array));Copy the code

There are several methods of array de-duplication

const arr = [1, 2, 1, 2, 3, 4, 2, 1, 3];

// 1 ES6
let newArr = [...new Set(arr)];

// 2
const arr = [1, 2, 1, 2, 3, 4, 'l', 2, 1, 3, 'l'];
const newArr = arr.filter(function(ele, index, array) {
	return index === array.indexOf(ele)
});
console.log(newArr); // [ 1, 2, 3, 4, 'l' ]

// 3
Array.prototype.unique2 = function() {
    let newArr = [];
    let len = this.length;
    for(let i = 0; i < len; i++) {
        let cur = this[i];
        if(newArr.indexOf(cur) === -1) {
            newArr[newArr.length] = cur;
        }
    }
    return newArr;
}
console.log(arr.unique1());

// 4
Array.prototype.unique3 = function() {
    let newArr = this.slice(0);
    let len = this.length;
    let obj = {};
    for(let i = 0; i < len; i++) {
        let cur = newArr[i];
        if(obj[cur]) {
            newArr[i] = newArr[newArr.length - 1];
            newArr.length--;
            i--;
            continue;
        }
        obj[cur] = cur;
    }
    return newArr;
}
console.log(arr.unique3());

// 5
Array.prototype.unique4 = function() {
    let json = {}, newArr = [], len = this.length;
    for(var i = 0; i < len; i++) {
        let cur = this[i];
        if (typeof json[cur] == "undefined") {
            json[cur] = true;
            newArr.push(cur)
        }
    }
    return newArr;
}
console.log(arr.unique4());
Copy the code

Micrometer operator

Methods a

// handle numbers let str1 = 2123456789; Let str2 = 2123456789.12; console.log(str1.toLocaleString()); / / 2123456789. The console log (str2 toLocaleString ()); / / 2123456789.12Copy the code

Method 2

// handle string let str1 = '2123456789'; Let str2 = '2123456789.12'; Function thousandth(STR) {let reg = /\d(? = (? :\d{3})+(? :\.\d+|$))/g; return str.replace(reg, '$&,'); } console.log(thousandth(str1)); / / 2123456789 console. The log (thousandth (str2)); / / 2123456789.12Copy the code

If (a == 1&a == 2&a == 3)

var a = {
  a: 1,
  valueOf() {
    return this.a++
  }
}

if (a == 1 & a == 2 & a == 3) {
  console.log(1)
}
Copy the code

In an array such as a and B, ensure that the sum of the difference of a and B and the difference of the index of a and B is the maximum value of the other two items in the array.

Let Max = (a – b) + (index of a – index of b); O b,

The answer:

/ / ideas: Let result = (maxitem-minitem) + (maxindex-minindex); let result = (maxitem-minitem) + (maxindex-minindex (maxItem+maxIndex) - (minItem+minIndex) // let arr = [1, 2, 3, 4, 5, 6]; 1 (6+5) - (1+0) = 10 // let arr = [2, 10, 1] 9, 1, 8, 3, 4]; let minItem = arr[0]; // let maxItem = arr[0]; let maxItem = arr[0]; Let min = minItem; // Let min = minItem; // let Max = maxItem; // let minIndex = 0; // let maxIndex = 0; For (let I = 1; i < arr.length; i++) { let cur = arr[i] + i; // The sum of the current item and its index cur < minItem? (minItem = cur, min = arr[i], minIndex = i) : null; cur > maxItem ? (maxItem = cur, max = arr[i], maxIndex = i) : null; } console.log(maxItem, minItem); // Maximum and index and minimum and index console.log(Max, min); // Maximum item minimum item console.log(maxIndex, minIndex); // Index of the largest item Index of the smallest itemCopy the code

Checks whether parenthesis expressions in strings are balanced

// balance('[()') = false; The balance (' [() () ()] ') = true / / a function match (a, b) { return (a === '(' && b === ')') || (a === ')' && b === '(') || (a === '[' && b === ']') || (a === ']' && b === '['); } function balance(str) { if (str.length % 2 === 0) { let len = str.length; for (let i = 0, j = len - 1;  i < len / 2; i++, j--) { if (! match(str[i], str[j])) { return false; } } return true; } return false; } console.log(balance('[()()()]'));  // true console.log(balance('[()')); // false console.log(balance('[]()')); Function is_balance(STR) {return [... STR]. Reduce ((stack, c) => {match(stack[stack.length-1], c) ? stack.pop() : stack.push(c); return stack; }, []).length === 0; } console.log(is_balance('[()()()]'));  // true console.log(is_balance('[()')); // false console.log(is_balance('[]()')); // falseCopy the code

The sum of three number

// The sum of three numbers
const threeSum = (nums) = > {
  nums.sort((a, b) = > a - b)

  const result = []
  for (let i = 0, len = nums.length; i < len; i++) {
    if (nums[i] > 0) break
    // Repeated values are omitted
    if (i > 0 && nums[i] === nums[i - 1]) continue
    let l = i + 1 / / pointer to the left
    let r = len - 1 / / right pointer
    while (l < r) {
      const sum = nums[i] + nums[l] + nums[r]
      if (sum > 0) {
        r--
      } else if (sum < 0) {
        l++
      } else { / / = = = 0
        result.push([nums[i], nums[l], nums[r]])
        // The next item is a duplicate value skipped
        while (l < r && (nums[l] === nums[l + 1])) l++
        // The next item is a duplicate value skipped
        while (l < r && (nums[r] === nums[r - 1])) r--
        l++
        r--
      }
    }
  }
  return result
}
Copy the code

Find the maximum sum of two adjacent terms

// let arr1 = [-1, 3, 1, -5, 2]; Function sum(arr) {let prev = arr[0]; let sumArr = []; let len = arr.length; for(let i = 1; i < len; i++) { let cur = arr[i]; sumArr.push(cur + prev); prev = cur; } return Math.max(... sumArr); } console.log(sum(arr1)); // function maxsum(arr) {const M = [arr[0]]; let max = M[0]; for(let i = 1; i < arr.length; i++) { M[i] = Math.max(arr[i], M[i - 1] + arr[i]); max = Math.max(M[i], max); } return max; }Copy the code

String to remove adjacent duplicates such as’ aabBCCDDeExxxxAA ‘=> ‘abcdexa’

// let STR = 'aabbccddeexxxxaa'; function uniq1(str) { // return str.replace(/([a-z])(\1){1,}/g, '$1'); return str.replace(/(.) (? =\1)/g, ''); } console.log(uniq1(str)); Function uniq2(STR) {let arr = str.split(''); let newArr = [arr[0]]; for(let i = 1; i < arr.length; i++) { let cur = arr[i]; if (cur ! == newArr[newArr.length - 1]) { newArr.push(cur); } } return newArr.join(''); } console.log(uniq2(str));Copy the code

Attributes combination

const permutation = (attr) = > {
  const ans = [], keys = Object.keys(attr)
  function dfs(tmp, cur) {
      if (keys.length === cur) return ans.push(tmp.slice());
      const key = keys[cur], arr = attr[key];
      for (let i = 0; i < arr.length; i++) {
          tmp.push(`${key}:${arr[i]}`);
          dfs(tmp, cur + 1);
          tmp.pop();
      }
  }
  dfs([], 0);
  return ans;
}
console.log(permutation(attr))
/ / /
// [ 'color:white', 'size:large', 'type:oversize' ],
// [ 'color:white', 'size:large', 'type:suit' ],
// [ 'color:white', 'size:large', 'type:tight' ],
// [ 'color:white', 'size:medium', 'type:oversize' ],
// [ 'color:white', 'size:medium', 'type:suit' ],
// [ 'color:white', 'size:medium', 'type:tight' ],
// [ 'color:white', 'size:small', 'type:oversize' ],
// [ 'color:white', 'size:small', 'type:suit' ],
// [ 'color:white', 'size:small', 'type:tight' ],
// [ 'color:red', 'size:large', 'type:oversize' ],
// [ 'color:red', 'size:large', 'type:suit' ],
// [ 'color:red', 'size:large', 'type:tight' ],
// [ 'color:red', 'size:medium', 'type:oversize' ],
// [ 'color:red', 'size:medium', 'type:suit' ],
// [ 'color:red', 'size:medium', 'type:tight' ],
// [ 'color:red', 'size:small', 'type:oversize' ],
// [ 'color:red', 'size:small', 'type:suit' ],
// [ 'color:red', 'size:small', 'type:tight' ],
// [ 'color:blue', 'size:large', 'type:oversize' ],
// [ 'color:blue', 'size:large', 'type:suit' ],
// [ 'color:blue', 'size:large', 'type:tight' ],
// [ 'color:blue', 'size:medium', 'type:oversize' ],
// [ 'color:blue', 'size:medium', 'type:suit' ],
// [ 'color:blue', 'size:medium', 'type:tight' ],
// [ 'color:blue', 'size:small', 'type:oversize' ],
// [ 'color:blue', 'size:small', 'type:suit' ],
// [ 'color:blue', 'size:small', 'type:tight' ]
// ]
Copy the code

Resource sharing

JavaScript Basics online tutorial documentation

From scratch – Create a complete online JavaScript tutorial document

Github implements some principles

  • A binary search tree traverses the values in the tree in order, first, and last order
  • Vue design principle is simple implementation: data hijacking, dependency collection, template compilation, bidirectional binding, computing properties
  • Spa single page routing design simple implementation
  • Browser cache interaction implementation
  • NPM release li-server static server written
  • The Node Events module implements publish subscriptions

JavaScript data structures and algorithms PDF resources

Baidu network disk password: LL8D

Fear of handwritten code 😨 can only bite the bullet

Welcome everyone to add with me a lot of the above can also be optimized I am still a growing white, just share and record their own problems will continue to update…