Write the new operator by hand

function myNew(fn, ... args) {
    let obj = {};
    obj.__proto__ = fn.prototype;
    letres = fn.call(obj, ... args);if (res && (typeof res === "object" || typeof res === "function")) {
        return res;
    }
    return obj;
}
// Test the code
function Person(name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.say = function() {
  console.log(this.age);
};
let p1 = myNew(Person, "lihua".18);
p1.say();
Copy the code

2. Implement an Instanceof

function Instanceof(left, right) {
    let leftVal = left.__proto__;
    let rightVal = right.prototype;
    while(leftVal ! = =null) {
        if (leftVal === rightVal){
            return true;
        }
        leftVal = leftVal.__proto__;          // Continue to find the prototype chain
    }
    return false;
}
// Test the code
console.log(Instanceof([], Array));
console.log(Instanceof([], Object));
Copy the code

3. Implement deep copy

function deepClone(objData) {
    let result = Array.isArray(objData) ? [] : {};
    for (let i in objData) {
        if (objData.hasOwnProperty(i)) {
            result[i] = typeof objData[i] === "object"? deepClone(objData[i]) : objData[i]; }}return result;
}
// Test the code
var obj1 = {
    a: 1.b: {
        a: 2.c: {
          name: 'jack'.age: 12}}};var obj2 = deepClone(obj1);
console.log(obj1);
Copy the code

4. Array implementation — Reduce implementation

Array.prototype.myReduce = function (fn, initvalue) {
    if(Object.prototype.toString.call(fn) ! = ="[object Function]" ) {
        throw new Error('The first argument must be a function');
    }
    // The second argument is optional
    let pre = null;
    if (arguments.length > 1) {
        pre = initvalue
    } else {
        pre = this[0];
    }
    // Iterate fn method:
    for (let i = 0; i < this.length; i++) {
        pre = fn(pre, this[i], i, this);
    }
    return pre;
}
// Test the code
let arr = [1.2.3];
let result = arr.myReduce((pre, cur) = > {
    return pre + cur;
}, 0)
console.log(result);
Copy the code

5. Array implementation of — filter implementation

Array.prototype.myFilter = function(fn) {
    if(Object.prototype.toString.call(fn) ! = ="[object Function]") {
        throw new Error('The first argument must be a function');
    }
    let list = [];
    for(let i =0; i < this.length; i++) {
        let result = fn(this[i], i, this);
        if (result) {
            list.push(this[i]); }}return list;
}
// Test the code
console.log([2.4.6].myFilter(item= > item < 3));
Copy the code

6. Array implementation – map implementation

Array.prototype.myMap = function(fn) {
    if(Object.prototype.toString.call(fn) ! = ="[object Function]") {
        throw new Error('The first argument must be a function');
    }
    let list = [];
    for(let i = 0; i< this.length; i++) {
        let result = fn(this[i], i, this);
        list.push(result);
    }
    return list;
}
// Test the code
console.log([1.2.3.5].myMap(item= > item * 10));
Copy the code

7. Array implementation of — every implementation

Array.prototype.myEvery = function(fn) {
    if(Object.prototype.toString.call(fn) ! = ="[object Function]") {
        throw new Error('The first argument must be a function');
    }
    for(let i = 0; i< this.length; i++) {
        if(! fn(this[i], i, this)) {
            return false; }}return true;
}
// Test the code
console.log([1.2.3.5].myEvery(item= > item > 1));
Copy the code

8. Array flattening processing flat implementation (three ways)

// 1. Reduce method:
function flat01(arr) {
    if(! arr.length)return;
    return arr.reduce((pre, cur) = > {
        return Array.isArray(cur) ? [...pre, ...flat01(cur)] : [...pre, cur]
    }, [])
}
// 2.
function flat02(arr) {
    if(! arr.length)return;
    let result = [];
    for(let i of arr) {
        if(!Array.isArray(i)) {
            result.push(i);
        } else{ result = [...result, ...flat02(i)]; }};return result;
}
// 3. General array implementation
function flat03(arr) {
    if(! arr.length)return;
    while(arr.some(item= > Array.isArray(item))) { arr = [].concat(... arr); };return arr;
}

// Test the code
console.log(flat01([1.2[1[2.3[4.5[6]]]]]));
console.log(flat02([1.2[1[2.3[4.5[6]]]]]));
console.log(flat03([1.2[1[2.3[4.5[6]]]]]));
Copy the code

9. Application of function Curryization — Curry

// Function corrification -- The technique of converting a function that takes multiple arguments into a series of functions that take one argument
function curry(fn) {
    if(fn.length <= 1) return fn;  // Determine the number of arguments passed to the function
    const result = (. args) = > {
        if(fn.length === args.length) {
            returnfn(... args); }else {
            return (. argsNew) = > {   // take arguments recursively and merge them until the number of arguments is the same as the number of fn arguments
                return result(...args, ...argsNew);
            }

        }
    }
    return result;
}
// Test the code
let add = (a, b, c, d) = > a + b+ c + d;
const curriedAdd = curry(add);
console.log(add(1.2.3.5));
console.log(curriedAdd(1) (2) (3) (5));
Copy the code

Implement the call method

Function.prototype.myCall = function (context, ... args) {
    if(! context || context ===null) {
        context = window;
    }
    let sym = Symbol(a); context[sym] =this; // The sym property of the context is used to call myCall.
    constresult = context[sym](... args);// Executing the function and returning the result is equivalent to calling itself as a method of the passed context
    delete context[sym];   // Delete this method, otherwise it will pollute the incoming object (add this method)
    return result;
}
// Test the code
function greet() {
    var reply = [this.animal, 'typically sleep between'.this.sleepDuration].join(' ');
    console.log(reply);
}
var obj = {
    animal: 'cats'.sleepDuration: '12 and 16 hours'
};
greet.myCall(obj);
Copy the code

Implement the Apply method

Function.prototype.myApply = function (context, args = []) {
    if(! context || context ===null) {
        context = window;
    }
    // Create a unique key value for the internal method name of the context we construct
    let sym = Symbol(a); context[sym] =this;
    // Execute the function and return the result
    letresult = context[sym](... args);delete context[sym];
    return result;
};
// Test the code
function greet() {
    var reply = [this.animal, 'typically sleep between'.this.sleepDuration].join(' ');
    console.log(reply);
}
var obj = {
    animal: 'cats'.sleepDuration: '12 and 16 hours'
};
greet.myApply(obj);
Copy the code

Implement the bind method

Function.prototype.myBind = function(context, ... args) {
    const self = this;
    args = args ? args : [];
    return function() {
        let newArgs = [...arguments];
        returnself.apply(context, args.concat(newArgs)); }}// Test the code
function greet() {
    var reply = [this.animal, 'typically sleep between'.this.sleepDuration].join(' ');
    console.log(reply);
}
var obj = {
    animal: 'cats'.sleepDuration: '12 and 16 hours'
};
greet.myBind(obj)();
Copy the code

13. Implementation of Object.create()

// object.create () takes the parameter Object as a prototype of a newly created empty Object and returns it
// 1. Simple version
function myCreate(obj) {
    function CreateObj() {};
    CreateObj.prototype = obj;
    return new CreateObj();
}
// 2. Official version
if (typeof Object.create ! = ="function") {
    Object.create = function (proto, propertiesObject) {
        if (typeofproto ! = ='object' && typeofproto ! = ='function') {
            throw new TypeError('Object prototype may only be an Object: ' + proto);
        } else if (proto === null) {
            throw new Error("This browser's implementation of Object.create is a shim and doesn't support 'null' as the first argument.");
        }

        if (typeofpropertiesObject ! = ='undefined') throw new Error("This browser's implementation of Object.create is a shim and doesn't support a second argument.");

        function F() {}
        F.prototype = proto;

        return new F();
    };
}
// Test the code
let a = {
    name: 'jack'.age: 12
};
let b = myCreate(a);
console.log(b);    / / {}
console.log(b.name)   // "jack"
Copy the code

14. Realization of anti-shake and throttling functions

// Stabilization function -- continuous trigger in the last execution method, scenario: input box match
function debounce(fn, time) {
    let timer = null;
    return function () {
        if (timer) {
            clearTimeout(timer);
            timer = null;
        }
        timer = setTimeout(() = >{ fn(); }, time); }}// Throttling function - fires only once in a certain period of time, scenario: long list of scrolling throttles
function throttle(fn, time) {
    let isRuning = false;
    return function() {
        if(isRuning) {
            return;
        }
        isRuning = true;
        setTimeout(() = > {
            fn();
            isRuning = false;
        }, time)
    }
}
// Test the code
let fn = () = > {
    console.log('fffffff')}setInterval(debounce(fn, 500), 1000) // It is triggered after 1500ms for the first time and every 1000ms thereafter
setInterval(throttle(fn, 1000), 1500) // Start the timer task test
Copy the code

15. Write a simple Ajax request

function ajax(options) {
    let url = options.url
    const method = options.method.toLocaleLowerCase() || 'get';
    const async= options.async ! =false; // The default is asynchronous: true
    const data = options.data; // Carry parameters
    const xhr = new XMLHttpRequest();  // Initialize the XMLHttpRequest instance

    if (options.timeout && options.timeout > 0) {  // Request timeout
        xhr.timeout = options.timeout
    }

    return new Promise((resolve, reject) = > {
        xhr.ontimeout = () = > reject && reject('Request timed out');   // When the request times out, the onTimeout method is emitted; Throw an error
        xhr.onreadystatechange = () = > {
            if (xhr.readyState == 4) {
                if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
                    resolve && resolve(xhr.responseText);
                } else {
                    reject && reject();
                }
            }
        }
        xhr.onerror = err= > reject && reject(err);   // Catch an error message
        // Process parameter information:
        let paramArr = []
        let encodeData
        if (data instanceof Object) {
            for (let key in data) {
                paramArr.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
            }
            encodeData = paramArr.join('&')}// Get request processing
        if (method === 'get') {
            // Check whether the url already exists. And their locations
            const index = url.indexOf('? ')
            if (index === -1) url += '? '
            else if(index ! == url.length -1) url += '&'
            / / stitching url
            url += encodeData
        }

        xhr.open(method, url, async)
        if (method === 'get') {
            xhr.send(null);
        } else {
            // Post requires a request header
            xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded; charset=UTF-8')
            xhr.send(encodeData)
        }
    })
}
// Use method:
ajax({
    url: 'your request url'.method: 'get'.async: true.timeout: 1000.data: {
        test: 1.aaa: 2
    }
}).then(
    res= > console.log('Request successful:' + res),
    err= > console.log('Request failed:' + err)
)
Copy the code

Write a JSONP by hand

const jsonp = function (url, data) {
    return new Promise((resolve, reject) = > {
        // Initialize the url, construct the complete URL:
        let dataString = url.indexOf('? ') = = = -1 ? '? ' : ' ';
        let callbackName = `jsonpCB_The ${Date.now()}`;
        url += `${dataString}callback=${callbackName}`;
        if (data) {
            // There are request parameters to add to the URL in turn
            for (let k in data) {
                url += `${k}=${data[k]}`; }}// Create a script tag:
        let jsNode = document.createElement('script');
        jsNode.src = url;
        // Trigger callback, which removes the js label and the callback bound to the window
        window[callbackName] = result= > {
            delete window[callbackName]
            document.body.removeChild(jsNode)
            if (result) {
                resolve(result)
            } else {
                reject('No data returned')}}// The js load is abnormal
        jsNode.addEventListener('error'.() = > {
            delete window[callbackName]
            document.body.removeChild(jsNode)
            reject('JavaScript resource load failed ')},false)
        // Add js node to document, start request
        document.body.appendChild(jsNode)
    })
}
// Code implementation:
jsonp('http://192.168.0.103:8081/jsonp', {
    a: 1.b: 'heiheihei'
})
.then(result= > {
    console.log(result)
})
.catch(err= > {
    console.error(err)
})
Copy the code

17. Implement a simple publish and subscribe model (Implementation of EventEmitter)

class EventEmitter {
    constructor() {
        this.events = {};
    }
    // Event listener/subscribe
    on(type, callBack) {
        let callbacks = this.events[type] || [];
        callbacks.push(callBack);
        this.events[type] = callbacks;
    }
    // Unsubscribe
    off(type, callBack) {
        if (!this.events[type]) return;
        this.events[type] = this.events[type].filter(item= > {
            return item !== callBack;
        })
    }
    // Trigger the event
    emit(type, ... rest) {
        if (this.events[type] && this.events[type].length > 0) {
            for (let fn of this.events[type]) {
                fn(...rest);
            }
        } else {
            console.log('Event not fetched')}}// Trigger once
     once(type, callback) {
        let fn = function (. args) { callback(... args);this.off(type, fn);  // Unsubscribe after triggering once
        };
        this.on(type, wrapFun); }}// Test the code
const llzevent = new EventEmitter();
const handle = (. rest) = > {
    console.log(rest);
};
llzevent.on("click", handle);
console.log(llzevent)
llzevent.emit('click'.1.2.4);
Copy the code

Implement a generic event listener function

const EventUtils = {
  / / add event (sight) respectively using dom0 | | dom2 | | IE three ways to bind an event)
  addEvent: function(element, type, handler) {
    if (element.addEventListener) {
      element.addEventListener(type, handler, false);
    } else if (element.attachEvent) {
      element.attachEvent("on" + type, handler);
    } else {
      element["on"+ type] = handler; }},// Remove the event
  removeEvent: function(element, type, handler) {
    if (element.removeEventListener) {
      element.removeEventListener(type, handler, false);
    } else if (element.detachEvent) {
      element.detachEvent("on" + type, handler);
    } else {
      element["on" + type] = null; }},// Get the event target
  getTarget: function(event) {
    return event.target || event.srcElement;
  },
  // Get a reference to the event object, get all the information about the event, and ensure that the event is always available
  getEvent: function(event) {
    return event || window.event;
  },
 // Prevent events (mainly event bubbling, since IE does not support event capture)
  stopPropagation: function(event) {
    if (event.stopPropagation) {
      event.stopPropagation();
    } else {
      event.cancelBubble = true; }},// Cancel the default behavior of the event
  preventDefault: function(event) {
    if (event.preventDefault) {
      event.preventDefault();
    } else {
      event.returnValue = false; }}};Copy the code

Implement an event delegate

<ul class="container">
    <li class="item">1231<span style="color: red">123131</span></li>
    <li class="item">8888</li>
    <li class="item">The third line</li>
    <li class="item"><div>In the fourth row</div></li>
</ul>

<script>
const container = document.querySelector(".container");
delegate(container, ".item"."click".(e, item) = > {
    console.log(item.textContent);
});
function delegate(container, itemSelector, event, handler) {
    container.addEventListener(event, (e) = > {
    let target = e.target;
        while(! target.matches(itemSelector) && target ! == container) { target = target.parentNode; }if (target !== container) {
            handler(e, target);
        }
    });
}
</script>
Copy the code

Implement a Scheduler asynchronous scheduler

// Simple version
class Scheduler {
    constructor(limit) {
        this.limit = limit
        this.number = 0
        this.queue = []
    }
    addTask(timeout, str) {
        this.queue.push([timeout, str])
    }
    start() {
        if (this.number < this.limit&&this.queue.length) {
            var [timeout, str] = this.queue.shift()
            this.number++
            setTimeout(() = > {
                console.log(str)
                this.number--
                this.start()
            }, timeout * 1000);
            this.start()
        }
    }
 }
// An asynchronous Scheduler Scheduler with concurrency limits that can limit the number of concurrent tasks
class Scheduler {
    constructor(maxCount) {
        this.maxCount = maxCount;
        this.queue = [];
        this.runCounts = 0;
    }
    // Add a task queue
    add(time, order) {
        const promiseCreator = () = > {
            return new Promise((resolve, reject) = > {
                setTimeout(() = > {
                    console.log(order);
                    resolve();
                }, time)
            })
        }
        this.queue.push(promiseCreator);
    }
    // Start task scheduling:
    taskStart() {
        for (let i = 0; i < this.maxCount; i++) {
            this.request(); }}request() {
        if (!this.queue || !this.queue.length || this.runCounts >= this.maxCount) {
            return;
        }
        this.runCounts ++;
        this.queue.shift()().then(() = > {
            this.runCounts --;
            this.request(); }}})// Test the code
const scheduler = new Scheduler(2);
const addTask = (time, order) = > {
  scheduler.add(time, order);
};
addTask(1000."1");
addTask(500."2");
addTask(300."3");
addTask(400."4");
scheduler.taskStart();
Copy the code

Implement a drag-and-drop div

<div class="box"></div>
<style>
      .box {
        position: absolute;
        width: 100px;
        background-color: red;
        height: 100px;
        left: 0;
        top: 0;
      }
</style>
<script>
      let lastPosition = [];
      const boxEle = document.querySelector(".box");
      let isDraging = false;
      boxEle.addEventListener("mousedown".(e) = > {
        isDraging = true;
        lastPosition[0] = e.clientX;
        lastPosition[1] = e.clientY;
      });
      document.addEventListener("mousemove".(e) = > {
        if(! isDraging)return;
        const deltaX = e.clientX - lastPosition[0];
        const deltaY = e.clientY - lastPosition[1];
        const curLeft = parseInt(boxEle.style.left || 0);
        const curTop = parseInt(boxEle.style.top || 0);
        boxEle.style.cssText = `left: ${curLeft + deltaX}px; top:${curTop + deltaY}px`;
        lastPosition[0] = e.clientX;
        lastPosition[1] = e.clientY;
      });
      document.addEventListener("mouseup".() = > {
        isDraging = false;
      });
</script>
Copy the code

Make a Promise come true

class MyPromise {
    constructor(func) {
        this.status = 'pending'
        this.result = undefined;
        this.error = undefined;

        this.resoledCallbacks = [];
        this.rejectedCallbacks = [];

        const resolve = (result) = > {
            this.status = 'resolved'
            this.result = result;
            setTimeout(() = > {
                this.resoledCallbacks.forEach((callback) = > callback())
            })
        };
        const reject = (error) = > {
            this.status = 'rejected'
            this.error = error;
            setTimeout(() = > {
                this.rejectedCallbacks.forEach((callback) = > callback())
            })
        };
        try {
            func && func(resolve, reject);
        } catch (err) {
            this.status = 'rejected';
            this.error = err; }}then(resolveCallback, rejectedCallback) {
        return new MyPromise((resolve, reject) = > {
            setTimeout(() = > {
                if (this.status === 'resolved') {
                    this.onResolve(resolveCallback, resolve, reject);
                } else if (this.status === 'rejected') {
                    this.onReject(rejectedCallback, resolve, reject);
                } else {
                    this.resoledCallbacks.push(() = > this.onResolve(resolveCallback, resolve, reject));
                    this.rejectedCallbacks.push(() = > this.onReject(rejectedCallback, resolve, reject)); }})})}catch(callback) {
        return new MyPromise((resolve, reject) = > {
            setTimeout(() = > {
                if (this.status === 'resolved') {
                    resolve(this.result);
                } else if (this.status === 'rejected') {
                    this.onReject(callback, resolve, reject);
                } else {
                    this.resoledCallbacks.push(() = > resolve(this.result));
                    this.rejectedCallbacks.push(() = > this.onReject(callback, resolve, reject)); }})})}finally(callback) {
        return new MyPromise((resolve, reject) = > {
            if (this.status === 'pending') {
                this.resoledCallbacks.push(() = > this.onFinally(callback, resolve, reject));
                this.rejectedCallbacks.push(() = > this.onFinally(callback, resolve, reject));
            } else {
                this.onFinally(callback, resolve, reject); }})}onResolve(callback, resolve, reject) {
        if(! callback)return resolve();
        try {
            const result = callback(this.result);
            if (result instanceof MyPromise) {
                result.then((res) = > {
                    resolve(res);
                }).catch((err) = >{ reject(err); })}else if (result instanceof Object && result.then instanceof Function) {
                result.then(res= >{ resolve(res); })}else{ resolve(result); }}catch (err) {
            reject(err)
        }
    }

    onReject(callback, resolve, reject) {
        if(! callback)return reject(this.error);
        try {
            const res = callback(this.error);
            resolve(res)
        } catch(err) { reject(err); }}onFinally(callback, resolve, reject) {
        try {
            callback && callback();
            if (this.status === 'resolved') resolve(this.result);
            if (this.status === 'rejected') reject(this.error);
        } catch (err) {
            reject(err)
        }
    }
}
Copy the code

All, promise.race, promise.any, promise.resolve, promise.reject

function resolve(val) {
    if (val instanceof Promise) return val;
    if (val && val.then instanceof Function) { 
        return new Promise(val.then); 
    };
    return new Promise((resolve) = > resolve(val));
}

function reject(val) {
    return new Promise((resolve, reject) = > reject(val))
}

function all(promiseArr) {
    return new Promise((resolve, reject) = > {
        if(!Array.isArray(promiseArr)) {
            reject(new Error('Parameter transfer error'))}let res = [];       // Collect information
        let counter = 0;
        for(let i = 0; i< promiseArr.length; i++) {
            Promise.resolve(promiseArr[i]).then((data) = > {
                counter ++;
                res.push(data);
                if(counter === promiseArr.length) {
                    resolve(res);
                }
            }).catch(error= > {
                reject(new Error('failure')); })}})}function race(promiseArr) {
    return new Promise((resolve, reject) = > {
        if(!Array.isArray(promiseArr)){
            return reject(new Error('The argument passed in must be an array'));
        }
        for(let i = 0; i< promiseArr.length; i++) {Promise.resolve(promiseArr[i]).then((data) = > {
                resolve(data);
            }).catch(error= > {
                reject(new Error('failure')); })}})}function any(promises) {
    const errors = []
    let count = 0;
    return new Promise((resolve, reject) = > {
        for (let i = 0; i < promises.length; i++) {
            promises[i].then((result) = > {
                resolve(result)
            }).catch((err) = > {
                errors[i] = err;
                count++;
                if (count === promises.length) {
                    reject(errors)
                }
            })
        }
    })
}

module.exports = {
    resolve,
    reject,
    all,
    race,
    any
}
Copy the code

24. Implement parasitic combination inheritance (ES5, ES6 version)

/ / es5 version
function Father(name) {
    this.name = name;
}
Father.prototype.printName = function() {
    console.log(this.name);
}
function Son(age) {
   this.age = age;
   Father.call(this); 
}
Son.prototype = Object.create(Father.prototype); // take Father. Prototype as the prototype of a newly created empty object and return the empty object
Son.prototype.constructor = Son;

/ / es6 version
class Father {
    constructor(name) {
        this.name = name;
    }
    printName() {
        console.log(this.name); }}class Son extends Father{
    constructor(name, age) {
        super(name);
        this.age = age;
    }
    printAll() {
        console.log(this.name, this.age); }}Copy the code

25. Implement a sleep function

/ / setTimeout version
const sleep = (fn, wait = 1000) = > {
    return function() {
        setTimeout(() = > {
            fn.apply(this.arguments);
        }, wait)
    } 
}
// async/await version
const sleep = async function(fn, wait, ... args) {
    const innerFunc = () = > {
        setTimeout(() = >{ fn(... args); }, wait) }await innerFunc();
}
/ / promise version
const sleep = (wait = 1000) = > {
    return new Promise((resolve) = > {
        setTimeout(resolve, wait)
    })
}
Copy the code

26. Bubble sort

function bubbleSort(arr) {
    let length = arr.length;
    for(let i =0; i< length; i++) {
        for(let j = i; j< length; j++) {
            if(arr[j] > arr[j+1]) {
                [arr[j], arr[j+1]] = [arr[j+1], arr[j]]; }}}return arr;
}
Copy the code

27. Select sort

function selectSort(arr) {
    let length = arr.length;
    let minIndex;    // Cache the smallest value index
    for(let i = 0; i< length; i++) {
        minIndex = i;
        for(let j = i; j< length; j++) {
            if(arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        }
        [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
    }
    return arr;
}
Copy the code

28. Quicksort

function quickSort(arr) {
    if(arr.length < 2) {
        return arr;
    }
    let cur = arr[arr.length -1];  // Select a value as the value of the cut-off point, or arr[0]
    let leftarr = arr.filter((item, index) = >item <= cur && index ! == arr.length -1);
    let rightArr = arr.filter((item, index) = >item >= cur && index ! == arr.length -1);
    return [...quickSort(leftarr), cur, ...quickSort(rightArr)];
}
Copy the code

29. Dichotomy to find an element in an array

function searchVal(arr, val, left = 0, right = arr.length - 1) {
    let midIndex = parseInt((left + right) / 2.10);
    if (val > arr[midIndex]) {
        return searchVal(arr, val, midIndex + 1, right);
    } else if (val < arr[midIndex]) {
        return searchVal(arr, val, left, midIndex - 1);
    } else {
        returnmidIndex; }}// Test the code
let arr = [1.4.5.66.7.8.34.4344.67];
console.log(searchVal(arr, 4));
Copy the code

30. Implement a Lazyman

/ / a: lazyMan (' Tony ') eat (' lunch '). Sleep (10) eat (' dinner ');
// Hi I am Tony
// I am eating lunch
// Wait 10 seconds...
// I am eating diner
class LazyManClass {
    constructor(name) {
        this.name = name;
        this.queue = [];
        console.log(`HI i am The ${this.name}`);
        setTimeout(() = > {
            this.next();
        }, 0)}eat(food) {
        const fn = () = > {
            console.log(`I am eating ${food}`);
            this.next();
        }
        this.queue.push(fn);
        return this;
    }
    sleep(time) {
        const fn = () = > {
            setTimeout(() = > {
                console.log(` waited${time}Seconds... `);
                this.next();
            }, time * 1000);
        }
        this.queue.push(fn);
        return this;
    }
    next() {
        // Spawn the first task in the queue and execute:
        const fn = this.queue.shift(); fn && fn(); }}// Code test:
function lazyMan(name) {
    return new LazyManClass(name);
}
lazyMan('Tony').sleep(5).eat('lunch');
Copy the code

31. LRU cache elimination algorithm

// LRU algorithm: get data and write data. When writing data, if the key exists, the data value will be changed, and if it does not exist, the data value will be inserted. When caching to the upper limit ==, the first data written should be deleted before writing new data
class LRUCache {
    constructor(size) {
        this.size = size;            / / capacity
        this.secretKey = new Map(a);// Create a dictionary of key values
    }
    / / value
    get(key) {
        if(this.secretKey.has(key)) {
            let templateValue = this.secretKey.get(key);
            // Delete it and set it again
            this.secretKey.delete(key);
            this.secretKey.set(key, templateValue);
            return templateValue;
        } else {
            return -1; }}/ / update
    put(key, value) {
        if(this.secretKey.has(key)) {
            this.secretKey.delete(key);
            this.secretKey.set(key, value);
        } else if(this.secretKey.size < this.size) {
            this.secretKey.set(key, value);
        } else {
            this.secretKey.set(key, value);
            this.secretKey.delete(this.secretKey.keys().next().value); }}}Copy the code