The sorting

Quick sort

function qSort(arr){
        if (arr.length == 0) {
            return [];
        }
        var left = [];
        var right = [];
        var pivot = arr[0];
        for (var i = 1; i < arr.length; i++) {
            if (arr[i] < pivot) {
                left.push(arr[i]);
                } else{ right.push(arr[i]); }}return qSort(left).concat(pivot, qSort(right));
    }
    // var a = [];
    // for (var i = 0; i < 10; ++i) {
    // a[i] = Math.floor((Math.random()*100)+1);
    // }
    // console.log(a);
    // console.log();
    // console.log(qSort(a));

    var a = [1.3.2];
    var b = [4.5.6]
    var c = 7;
    console.log([...a,c,...b]);  // [1, 3, 2, 7, 4, 5, 6]
Copy the code

Insertion sort

/* Best case: T(n) = O(n2) Worst case: T(n) = O(n2) Average case: T(n) = O(n2) Principle of the algorithm: the outer loop moves the array elements one by one, while the inner loop compares the selected element in the outer loop with the element after it. If the selected element in the outer loop is smaller than the selected element in the inner loop, then the set of elements moves to the right to make room for the element in the inner loop, just like the last name card introduced earlier. Selection sort and insert sort are faster than bubble sort, and insert sort is the fastest of the three. * /

function insertSort(array) {
    var i, j, temp, n = array.length;
    for (i = 1; i < n; i++) {
        j = i - 1; temp = array[i];
        while (j < i && array[j] > temp) {
            array[j + 1] = array[j];
            j--;
        }
        array[j + 1] = temp;

    }
    return array;
}
var arrayA = [1.3.2.6.4.5];
console.log(insertSort(arrayA));

function insertSort(arr) {
    var temp;  // The temp variable is used to temporarily store elements to be inserted
    for (var i = 1; i < arr.length; i++) {
        temp = arr[i];
        // find the insertion position from front to back
        for (var j = i; j > 0 && arr[j - 1] > temp; j--) {
            arr[j] = arr[j - 1]; // Move arr[j] elements greater than temp back
        }
        arr[j] = temp;Arr [j]=temp, not arr[j-1]=temp}}/ / test
var testArr = [35.22.1.56.88.25];
insertSort(testArr);
console.log(testArr);

/** ** data structure book ** * sort one item at a time, this way to build the final sorted array. Assuming the first term is sorted, and then comparing it to the second term, should the second term stay in place or be inserted before the first term? This way, the first two items are sorted correctly, and then compared to the third item (should it be inserted first, second, or third?). And so on. * * for example, the first line of the algorithm identifies the variables used in the code (line {1}). Next, the algebraic group finds the correct (line {2}) for the ith term. Note that the algorithm starts from the second (index 1), not 0 (we sorted the first item). It then initializes a helper (line {3}) with the value of I and stores its value in a time variable (line {4}) so that it can be inserted into the correct one later. The next step is to find the right entry project. To make the variable j greater than 0 (because the first index of the array is 0 -- there is no value index) and the previous value in the array is greater than the comparison value (line {5}), we bring the value to the current value (line {6}) and decrease j. Finally, the project gets to the right place. * /

// this.insertionSort = function () {
// var length = array.length,
// j, temp;
// for (var i = 1; i < length; i++) {

// j = i;
// temp = array[i];
// while (j > 0 && array[j - 1] > temp) {
// array[j] = array[j - 1];
// j--;
/ /}
// array[j] = temp;
/ /}
// }

Copy the code

Bubble sort


/* Compares two adjacent values in sequence, and if the following is smaller than the preceding, ranks the smaller element first. Follow this rule for multiple, decreasing iterations until the order is correct. Average time complexity O(n*n) best case O(n) Worst case O(n*n) Space complexity O(1) Stability: Stable */
/** * Algorithms in javascript data structures ** /

// var swap = function(index1, index2){
// var aux = array[index1];
// array[index1] = array[index2];
// array[index2] = aux;
// };

// var bubbleSort = function () {
// var length = array.length;
// for (var i = 0; i < length; i++) {
// for (var j = 0; j < length - 1; j++) {
// if (array[j] > array[j + 1]) {
// swap(j, j + 1);
/ /}
/ /}
/ /}
// }


// function bubbleSort(arr) {
// var len = arr.length;
// var temp;

// for ( var i = len; i > 1; --i) {
// for ( var j = 0; j < i ; ++j ) {
// if (arr[j] > arr[j + 1]) {
// swap(arr, j, j + 1);
/ /}
/ /}
/ /}
// }
// function swap(arr, index1, index2) {
// var temp = arr[index1];
// arr[index1] = arr[index2];
// arr[index2] = temp;
// }

/** * Improved bubble sort: All unnecessary comparisons in the inner loop can be avoided if the number of runs in the outer loop is subtracted from the inner loop */
// Control the inner loop, inner loop arr. Length-1-i, compare the rest with that element
// Output from small to large

function bubbleSort(arr) {
    for (var i = 0; i < arr.length - 1; i++) {
        for (var j = 0; j < arr.length - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
                var temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp; }}}return arr;
}

var arr = [8.94.15.88.55.76.21.39];
bubbleSort(arr);
console.log(arr);
Copy the code

Selection sort

/* Best case: T(n) = O(n2) Worst case: T(n) = O(n2) Average case: T(n) = O(n2) Algorithm principle: - Selection sort starts at the beginning of the array and compares the first element with other elements. - After checking all the elements, the smallest element is placed in the first position of the array, and the algorithm continues from the second position. - This process continues until you reach the penultimate position of the array and all the data is sorted. * /


function selectSort(arr) {
	var len = arr.length;
	var index, temp;
	for (var i = 0; i < len - 1; i++) {   // The loop moves from the first element of the array to the penultimate element
		index = i;   // Initialize the minimum index
		for (var j = i + 1; j < len; j++) {  // The inner loop moves from the second element to the last element
			if (arr[j] < arr[index]) {// Find the smallest number and compare the first element with other elements
				index = j;// Save the smallest index, always keep the smallest index position change (that is, the position of the following value smaller)
			}
		}
		temp = arr[i];   //arr[I] is the value to be compared
		arr[i] = arr[index];
		arr[index] = temp;    // Swaps the resulting index value (the inner loop index value, the j value (index value) is not equal to the I value) with the value being compared
	} // Initialize the minimum index
	return arr;
}

var arr = [8.94.15.88.55.76.21.39];
console.log(selectSort(arr));

/** * Selection sort is also an O(n2) algorithm. Like bubble sort, it contains two nested loops, which leads to quadratic complexity. However, insert sort, which we'll learn next, performs better than selection sort. * /
// this.selectionSort = function () {
// var length = array.length,
// indexMin;
// for (var i = 0; i < length - 1; i++) {
// indexMin = i;
// for (var j = i; j < length; j++) {
/ /}
/ /}
// if (array[indexMin] > array[j]) {
// indexMin = j;
// if (i ! == indexMin) {
// swap(i, indexMin);
/ /}
/ /}
// };
Copy the code

Hill sorting

/* Hill sort is to group the records in increments of the index, and sort each group using the direct insertion sort algorithm; As the increments decrease, each group contains more and more keywords, and when the increments decrease to 1, the entire file is exactly grouped and the algorithm terminates. * /
function shellSort(arr) {
	let l = arr.length;
    let gap = l >> 1;
    
    while(gap>0) {
        for(leti = gap; i<l; i++) {let tem = arr[i];
            let j = i - gap; 
            for(; j>=0&&tem<arr[j]; j-=gap){ arr[j+gap] = arr[j]; } arr[j+gap] = tem; } gap = gap >>1;
    }
    
    return arr;
}
Copy the code

Kerrization of JS functions

A new function technique that turns a function that takes multiple arguments into a function that takes one argument and returns a function that takes the rest and returns the result

Features: early return, parameter reuse, delay execution

function curry(fn, arg){
    let length = fn.length;
    let args = arg || [];
    return function (){
        let newArgs = args.concat(Array.prototype.slice.call(arguments));
        if (newArgs.length < length) {
            return curry.call(this,fn,newArgs);
        }else{
            return fn.apply(this,newArgs); }}}function multiFn(a, b, c) {
    return a * b * c;
}

var multi = curry(multiFn);

multi(2) (3) (4);
multi(2.3.4);
multi(2) (3.4);
multi(2.3) (4); <! -->function currying(fn){
    var allArgs = [];

    return function next(){
        var args = [].slice.call(arguments);

        if(args.length > 0){
          	
            allArgs = allArgs.concat(args);
            return next;
        }else{
          console.log(allArgs)
            return fn.apply(null, allArgs); }}}var add = currying(function(){
    var sum = 0;
    for(var i = 0; i < arguments.length; i++){
        sum += arguments[i];
    }
    return sum;
});

console.log(add(3) (4) ())3+4=7


Copy the code
const curry = (fn, arr = []) = > (. args) = > (
  arg= >arg.length === fn.length ? fn(... arg) : curry(fn, arg) )([...arr, ...args])let curryTest=curry((a,b,c,d) = >a+b+c+d)
curryTest(1.2.3) (4) / / return 10
curryTest(1.2) (4) (3) / / return 10
curryTest(1.2) (3.4) / / return 10



const curry = (fn, arr = []) = > (. args) = > {return (
  arg= >{returnarg.length === fn.length ? fn(... arg) : curry(fn, arg)} )([...arr, ...args])}Copy the code

Compose function, functional programming

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

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))) }function compose(. funcs){
  if (funcs.length === 0 ) arg => arg
  if (funcs.length === 1 ) funcs[0]
  return funcs.reduce((a,b) = > (. args) = >a(b(... args))) }const add = num= > num + 10
const multiple = num= >num * 3 
let result = compose(multiple,add)
result(5)


function compose(. funcs){
console.log(funcs)
  if(funcs.length===0) arg => 1
  if(funcs.length===1) { conssole.log(funcs[0] ())return funcs[0]}
  funcs.reduce((a,b) = >(. args) = >a(b(args)))


  function compose() {
    var fns = [].slice.call(arguments)
    return function (initialArg) {
        var res = initialArg
        for (var i = fns.length - 1; i > -1; i--) {
            res = fns[i](res)
        }
        return res
    }
}

const add = num= > num + 10
const multiple = num= >num * 3 
let result = compose(multiple,add)
result(5)


function compose() {
    var fns = [].slice.call(arguments)
    return function (initialArg) {
        var res = initialArg
        for (var i = fns.length - 1; i > -1; i--) {
            res = fns[i](res)
        }
        return res
    }
}

function pipe() {
    var fns = [].slice.call(arguments)
    return function (initialAgr) {
        var res = initialAgr
        for (var i = 0; i < fns.length; i++) {
            res = fns[i](res)
        }
        return res
    }
}

var greet = function (name) { return 'hi:' + name }
var exclaim = function (statement) { return statement.toUpperCase() + '! ' }
var transform = function (str) { return str.replace(/[dD]/.'DDDDD')}var welcome1 = compose(greet, exclaim, transform)
var welcome2 = pipe(greet, exclaim, transform)
console.log(welcome1('dot'))//hi:DDDDDOT!
console.log(welcome2('dolb'))//HI:DDDDDOLB!Compose's functions are executed from right to left, i.e. the rightmost function (the last parameter) is executed first, and the result of the execution is passed as an argument to the previous function (the function that wraps it) until the whole function is executed.returnA function, so compose's internal implementation works like a cascade of dominoes. Pipe function and compose function is very similar, is also a function after the completion of the results passed as a parameter to another function, but the difference only lies in the pipe function of receiving function parameters, from left to right, namely, the first parameter (function) has been completed will spit out the results passed as a parameter to a second function, Which is the second argument to pipe, until all of the pipe arguments have been executed as functions,returnWe're not done until we have a function. Compose and Pipe have the advantage of adding or removing even one more parameter (an execution function), simply adding or removing the corresponding parameter and the defined function, making it easy to maintain and extend.Copy the code

promise

function myPromise(construct){
    let self = this;
    self.status = 'pending';
    self.resolveVal = undefinded;
    self.rejectVal = undefinded;
    function resoved(resolveVal){
        if(self.status === 'pending'){
             self.resolveVal = resolveVal;
             this.status = 'resolved'}}function rejected(rejectVal){
        if(self.status === 'pending'){
             self.rejectVal = rejectVal;
             this.status = 'rejected'}}// Catch a construction exception
    try{
       constructor(resolve,reject);  // This sentence must not be less
    }catch(e){
       reject(e);
    }
}

myPromise.prototype.then=function(onFullfilled,onRejected){
   let self=this;
   switch(self.status){
      case "resolved":
        onFullfilled(self.value);
        break;
      case "rejected":
        onRejected(self.reason);
        break;
      default:}}var p=new myPromise(function(resolve,reject){resolve(1)});
p.then(function(x){console.log(x)})

Copy the code

instanceOf

The instanceof operator is used to test whether constructor. Prototype exists on the prototype chain of the parameter Object.

  1. The common use of instanceof, obj instanceof Object checks whether Object. Prototype exists on the prototype chain of the parameter obj.

  2. Inheritance determines whether an instance belongs to its parent class

  3. Complex usage

function instanceof(left,right){
    let proto = left.__proto__;
    let prototype = right.prototype;
    while(true) {if(proto === null) return false
        if(proto === prototype) return trueproto = proto.__proto__; }}Copy the code
Let the result = [{id: 1, name: 'the bank of China'}, {id: - 3, name: 'the bank'}, {id: 2, name: 'hebei Banks'}, {id: 10, name:' baoding Banks'}, {id:7,name:' laishui bank '}] function sortId(a,b){return a.id- a.id result.sort(sortId); console.log(Math.max.apply(Math,diffVal)); / / diffVal is an arrayCopy the code

Deep copy

Not only is a copy of the first level cloned for the new array/object, but if there are multiple levels in the original array, a copy of each level is cloned for each level assigned to the new array/object.

Json. parse and json.stringify

let arr2 = JSON.parse(JSON.stringify(arr1))

  • How it works: Convert the string to a string, and then convert the string to a new object, so that the browser reopens memory to store the information.

  • Application scenario: Numbers, strings, booleans, null, common objects, and array objects are not affected and can be used

Cons: Json.stringify (arR1) : Not all values are handled efficiently

[1] Regular will become empty objects [2] json. stringify(function, undefined, Symbol) will become undefined [3] json. parse(undefined) Object format cannot be returned based on parse

JSON.stringify(new Number(4))
"4"
JSON.stringify(new RegExp(/[a]/))
"{}"
JSON.stringify(new Date())
""2020-07-16T02:51:37.020Z""
JSON.stringify(function a(){})
undefined
JSON.stringify({a:1})
"{"a": 1}"
JSON.stringify([1.2.3])
"[1, 2, 3]"
JSON.stringify(undefined)
undefined
JSON.stringify(Symbol)
undefined
JSON.stringify(null)
"null"

JSON.parse(undefined)
// Uncaught SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at <anonymous>:1:6
JSON.parse(null) //null

var a=[1[2[44]], []]var obj = {
 userName1:1.userName2: {userAge1:1 
    },
   userAge13: {userAge1: {a: 3}}} can be deep copyCopy the code

Method two: own encapsulation

function deepClone(obj) {
    // Filter some special cases
    if(obj === null) return null;
    if(typeofobj ! = ="object") return obj;
    if(obj instanceof RegExp) { / / regular
         return new RegExp(obj);
    }
    if(obj instanceof Date) { / / date
         return new Date(obj);
    }
    // let newObj = {}
    // let newObj = new Object()
    let newObj = new obj.constructor; // The purpose of not creating an empty object directly: the result of cloning and the previous class = "can clone an ordinary object, but also can clone an instance object
    for(let key in obj) {
        if(obj.hasOwnProperty(key)) { newObj[key] = deepClone(obj[key]); }}// let newObj = obj.constructor === Array ? [] : {};
    //for(let key in obj) {
    // newObj[key] = Object.prototype.toString.apply(obj[key]) === '[object Object]' ? deepCopy(obj[key]) : //obj[key];
    / /}
    return newObj;
}
Copy the code

bind

Blog.csdn.net/q3254421/ar…

Input: takes one or more arguments, the first of which is the context to bind, and the additional arguments are used as prefixes to the binding function. Output: returns a copy of the original function, that is, a function that does what the original function does

To change this and return a function, call func.apply(this,arg) manually.

Function.prototype.myBind = function(obj){
    let _self = this // This represents the function being called
    if(typeof this! = ='function') {return
    }
    let arg1 = [].slice.call(argument,1);// The second argument intercepts the argument of the called function
    let fBound = function(){
        let arg2 = [].slice.call(argument);// Since bind returns a function, it may be followed by arguments
         // If this of the current function refers to this in the constructor, the operation is considered new, i.e. this is the instance object
        let realObj = this instansof _self ? this : obj  // The bound calling function can also be created by the new operation, in which case this is ignored
        return _self.apply(realObj,arg1.concact(arg2))
    }
    // Define an empty function as an intermediate bridge
    let emptyFun = function(){} // Create an empty function as a middleman, taking the prototype of the original function and throwing it to the binding function
    // Maintain prototype relationships
    if(this.prototype){
        emptyFun.prototype = this.prototype; // This is the original function, which is foo
    }
    fBound.prototype = new emptyFun() //fBound inherits emptyFun's prototype chain
    return fBound
}


function foo(name) {
    this.name = name;
}
var obj = {};  // Empty object pointing to window
var bar = foo.myBind(obj);
bar('Jack');  //Jack2 corresponds to arg2, pointing to window or undefinded is equivalent to window.foo('Jack'), where this.name is Jack
console.log(obj.name);  // Jack obj has the name attribute

var alice = new bar('Alice');
console.log(obj.name);  // Jack //realObj is obj
console.log(alice.name);    //realObj is the instance objectThe barthisTo:1The bar variable is the bound function, that is, fBound, and _self is a reference to foo2If I go straight to bar(' jack ') it points towindowundefined.3newBar (' Alice ') (equivalentnewFoo (' Alice ')) procedure, fBound'sthisPoints to thenewThe object returned by the expression Alice4If it isnewCall the binding function, when the binding functionthisIs made up ofnewThe instance object returned by calling the binding function. The constructor of this object is fnBound5When we ignore the prototype link line, the prototype object is not the prototype of self, sothis instanceof self ? this: oThis returns the value of the specified object, not thenewObject returnedCopy the code

new

Example created with new:

  • Can access properties in the constructor
  • Access to properties in the stereotype
function create(){
    // 1. Get the constructor and delete the first item in arguments
    let ConF = [].shift.call(arguments);
    // 2. Create an empty object and link it to the prototype of the constructor so that it can access properties in the prototype
    let obj = Object.create(ConF.prototype);
    // 3. Use apply to change the direction of this in the constructor to implement inheritance so that obj can access the attributes in the constructor
    let ref = ConF.apply(obj,arguments);
    // 4. Return the object returned by the constructor first
    return ref instanceof Object ? ref : obj
}
Copy the code

When you’re interviewing, you can say the object could be an instance object, it could be a context, it could be an object

call

Function.prototype.myCall = function(ctx){ context = (context ! == null && context ! == undefined) ? Object(context) : window; var fn = Symbol(); context[fn] = this; let args = [...arguments].slice(1); let result = context[fn](... args); delete context[fn]; return result; }Copy the code

apply

Function.prototype.apply3 = function(context, arr) {
    // 1. If context is passed in as null or undefined, point to window;
  // 2. If a primitive data type is passed in, the native call calls the Object() conversion
  context = context ? Object(context) : window; <! Create a unique name for the fn function -->let fn = Symbol(a); <! Here -thisContext [fn] = --> context[fn] =this;

  letresult = arr ? context[fn](... arr) : context[fn](); <! Context is attached with an additional attribute fn, so it needs to be deleted when it is used -->deletecontext[fn]; <! Function fn may have a return value, which needs to be returned -->return result;
};

Copy the code

jsonp

Zhangguixu. Making. IO / 2016/12/02 /…

Principle:

Using script SRC has no cross-domain restrictions. By pointing to a url that needs to be accessed, the server returns a pre-defined JS function call. The server takes the data to be returned to the function parameter, which needs to be completed with the front and back ends.

Implementation method:

  • The server returns a call to the function callback(res)
  • Create a Script tag with the requested Callbak name above the URL
  • The front end writes out the functions that need to be called

Disadvantages:

  • Only get requests
  • Prone to XSS vulnerabilities

Advantages:

  • Good compatibility, supported by many older browser versions
Node implements the server codelet http = require('http');
let urlLib = require('url');
let port = 8080;
let data = {'data':'world'};
http.createServe(function(req,res){
    var  params = urlLib.parse(req.url,true); // Get the requested URL
    if(params.query.callback){
        var str = params.query.callback + '(' + JSON.stringify(data) + ') ';
        res.end(str);
    }else{
        res.end();
    }
}).listen(port,function(){
    console.log('jsonp server is start'); }); The front-end codefunction jsonpFun(res){
    alert('hello ' + res.data);
}

function jsonp(res){
    let script = document.createElement('script');
    let url = res.url + '? callback=' + res.callback;
    let sript.url = url
    document.getElementsByTag('head') [0].appendChild(script)
}
jsonp({
    url:  "http://localhost:8080/a.com, callback: jsonpFun })Copy the code

cors

let express = require('express');
let app = express();
app.use(function(req,res,next){
    res.header('Access-Controll-Allow-Origin'.' ')
    res.header('Access-Controll-Allow-Headers'.'Content-type')
    res.header('Access-Controll-Allow-Method'.'PUT,POST,GET,OPTION,DELETE')})Copy the code

duplicate removal

function reducer(a){
  let hash = {};
  let b = a.reduce(function(arr, item){
    //item is an object or array
    hash[item] ? ' ' : hash[item]=true && arr.push(item)
	return arr
  },[])
  console.log( b) //[Object { a: 1 }, 2, Array [1, 2]]
}

reducer([{a:1}, {a:1},2.2[1.2], [1.2]])


Copy the code

Anti-shake and throttling

Throttling such as waiting at a bus stop and leaving every 30 minutes, regardless of whether there is someone else behind. This is the process of throttling.

Wait 30 minutes for the last passenger. If no one gets on within 30 minutes, the train will leave. If someone gets on during that time, wait another 30 minutes. That’s how it works.

Application scenarios

In the window resize, scroll, input box content verification and other operations.

Debounce: When an event is continuously triggered and no event has been triggered for a certain period of time, the event handler is executed once. If the event is triggered again before the specified time, the delay is restarted. As shown in the following figure, handle is not executed when the Scroll event is continuously triggered. The Scroll event will be delayed when no scroll event is triggered within 1000 milliseconds.

Function throttling: Ensures that event handlers are called only once in a certain period of time when events are continuously emitted. Throttling popular explanation is like our tap water, as soon as the valve is opened, the water pouring down, holding the good traditional virtue of thrift, we have to turn the tap down a little, it is best to be as we will according to a certain rule in a certain time interval drop by drop. As shown in the figure below, when the Scroll event is continuously triggered, handle is not executed immediately but only once every 1000 milliseconds.

Function throttling can be implemented in two main ways: timestamp and timer.

Mp.weixin.qq.com/s/Vkshf-nED…

Anti – shake: Prevents jitter. The event trigger can be reset within a unit time, preventing the event from being triggered multiple times by accidental injury. The code implementation focuses on clearing clearTimeout

Anti-shake scene:

1. The login and SMS buttons are clicked so fast that multiple requests are sent. When adjusting the browser window size, the number of resize times is too frequent, resulting in too much calculation. At this time, it needs to be in place once, so anti-shake 3 is used. The text editor saves in real time and saves after one second when there is no change operation

Throttling: Controls traffic. An event can be triggered only once per unit of time. Timer =timeout; timer=null

Throttling scenario: 1. Scroll event, calculate position information every second, etc. 2. Browser plays events, calculates progress information once every second, etc. 3. Input box searches and sends requests in real time to display the drop-down list, and sends requests every second (it can also be used for shaking prevention)

function debounce(fn,delay){
    let timer = null;
    return function(){
        let self = this;
        let args = argument;
        clearTimeout(timer);
        timer = setTimeout({
            fn.apply(self,args)
        },delay)
    }
}
Copy the code
The timervar throttle = function(func, delay) {
            var timer = null;
            return function() {
                var context = this;
                var args = arguments;
                if(! timer) { timer =setTimeout(function() {
                        func.apply(context, args);
                        timer = null; }, delay); }}}function handle() {
            console.log(Math.random());
        }
        window.addEventListener('scroll', throttle(handle, 1000));
Copy the code
Var throttle = function(func, delay) {var prev = date.now (); return function() { var context = this; var args = arguments; var now = Date.now(); if (now - prev >= delay) { func.apply(context, args); prev = Date.now(); } } } function handle() { console.log(Math.random()); } window.addEventListener('scroll', throttle(handle, 1000));Copy the code

Depth first and breadth first

Depth first

recursivefunction deepFirstTraverse(node,nodeList){
    if(node){
      nodeList.push(node)  
      let children = nodeList.children;
      for(let i=0,i<children.length; i++){ deepFirstTraverse(children[i],nodeList) } }returnNodeList} is non-recursivefunction deepFirstSearch(node) {
    var nodes = [];
    if(node ! =null) {
        var stack = [];
        stack.push(node);
        while(stack.length ! =0) {
        var item = stack.pop();
        nodes.push(item);
        var children = item.children;
        for (var i = children.length - 1; i >= 0; i--) stack.push(children[i]); }}return nodes;
}
Copy the code

breadth-first

function breadthFirstTraverse(node){
    var nodes = [];  
    if(node ! =null) {  
        var queue = [];  
        queue.unshift(node);  
        while(queue.length ! =0) {  
            var item = queue.shift();  
            nodes.push(item);  
            var children = item.children;  
            for (var i = 0; i < children.length; i++) queue.push(children[i]); }}returnnodes; } recursive versionfunction breadthFirstTraverse(node) {
    var nodes = [];
    var i = 0;
    if(! (node ==null)) {
        nodes.push(node);
        breadthFirstSearch(node.nextElementSibling);
        node = nodes[i++];
        breadthFirstSearch(node.firstElementChild);
    }
    return nodes;
}
Copy the code

Random color capture

Generate random colors through HSBvar getRandomColor = function(){
    return "hsb(" + Math.random()  + ", 1, 1)";
 }


function fn1(){
    return The '#' + Math.floor( Math.random() * 0xffffff ).toString(16);
}


function fn2(){
    return The '#' + ( Math.random() * 0xffffff<<0 ).toString(16);
}


function fn3(){
    var r = Math.floor( Math.random() * 256 );
    var g = Math.floor( Math.random() * 256 );    
    var b = Math.floor( Math.random() * 256 );
    return "rgb("+r+', '+g+', '+b+")";
}


function fn4(){
    var color = "#";
    for( var i = 0; i < 6; i++ ){
        color += ( Math.random()*16 | 0 ).toString(16);
    }
    return color;
}


function fn5(){
    var colorValue = "0,1,2,3,4,5,6,7,8,9, a, b, c, d, e, f";
    var colorArray = colorValue.split(",");
    var color = "#";
    for( var i = 0; i < 6; i++ ){
        color += colorArray[ Math.floor( Math.random() * 16)]; }return color;
}


Copy the code

Group the same elements into a new array

“js` var arr=[‘1′,’1′,’1′,’2′,,’3′,’4′,’5′,’5′,’6′,’6′,’7’, ‘8’,’9′,’9′,’10’]; var newArr1 = [], tempArr = []; for(var i=0,j=arr.length; i<j; i++){ if(arr[i] == arr[i+1]){ tempArr.push(arr[i]); } else { tempArr.push(arr[i]); newArr1.push(tempArr.slice(0)); tempArr.length = 0; } } console.log(newArr1);

Var _arr =,3,2,4,3,2,1,3,4,2 [1];

var _res = []; // _arr.sort(); for (var i = 0; i < _arr.length;) { var count = 0; for (var j = i; j < _arr.length; j++) { if (_arr[i] == _arr[j]) { count++; } } _res.push([_arr[i], count]); i += count; } console.log(_res); / / [[1, 2], [2, 3], [3, 3], Array [4, 2]] / / _res 2 dimension d saves the value and repeat number in var _newArr = []; for (var i = 0; i < _res.length; I++) {/ / the console. The log (_res [I] [0] + “repetition:” + _res [I] [1]). _newArr.push(_res[i][0] + ‘x’ + _res[i][1]); } console.log(_newArr);


https://juejin.cn/post/6844903809206976520
https://juejin.cn/post/6844903810113126413
https://juejin.cn/post/6844904096382582797#heading-95
Copy the code