Recently looking for an internship, on the record of some of their own peacetime see and interview process encountered code questions, if there is anything wrong or can be improved, I hope you criticize and correct ~

One, HTML, CSS related

1. Horizontal center


      
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
    <! Word-wrap: break-word! Important; "> < span style =" max-width: 100%; height:300px; background-color:blue; } .son{ width:100px; height:100px; background-color:yellow; margin:0 auto; Left + margin-left */ /*.father{width:500px; height:300px; background-color:blue; position:relative; } .son{ width:100px; height:100px; background-color:yellow; position:absolute; left:50%; margin-left:-50px; } */ </style> -->

    <! -- Block level element horizontally centered, element width unknown -->
    <style>
        Left + translateX(-50%) */
        /* .father{ width:500px; height:300px; background-color:blue; position:relative; } .son{ height:100px; background-color:yellow; position:absolute; left:50%; transform:translateX(-50%); overflow:hidden; text-overflow:ellipsis; } * /

        /* Flex */
        .father{
            width:500px;
            height:300px;
            background-color:blue;
            display:flex;
            justify-content:center;
        }
        .son{
            height:100px;
            background-color:yellow;
        }
    </style>
</head>
<body>
    <div class="father">
        <div class="son">I'm a block-level element</div>
    </div>
</body>
</html>
Copy the code

2. Center vertically


      
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
    <style>
        /* position method */
        /* .father{ width:300px; height:300px; background-color:red; position:relative; } .son{ width:100px; height:100px; background-color:blue; position:absolute; top:50%; transform: translateY(-50%); } * /

        /* Flex method */
        .father{
            background-color:blue;
            width:300px;
            height:300px;
            display:flex;
            align-items:center;
        }
        .son{
            width:100px;
            height:100px;
            background-color:red;
        } 
        
    </style>
</head>
<body>
    <div class="father">
        <div class="son">Vertical center</div>
        
    </div>
</body>
</html>
Copy the code

3. Obtain all checkboxes on the page

// Get all the checkboxes in the page. (do not use third-party frameworks) var inputs = document. The getElementsByTagName (" input "); var checkboxArray = []; for(let i = 0; i< inputs.length; i{+ +)if(inputs[i].type= = ="checkbox") {checkboxArray.push(inputs[i]); }}Copy the code

4. Table row color changes

<! Write a table with CSS so that the table has a white background for odd numbers, a gray background for even numbers, and a yellow background when you hover over it. -->

      
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>form</title>
    <style type="text/css">
        body {
            margin: 0;
        }

        table {
            border: 1px solid #ddd;
            border-collapse: collapse; /* Remove the gap between td */

        }

        tr:nth-child(odd) {
            background-color: #fff
        }

        tr:nth-child(even) {
            background-color: # 666
        }

        tr:hover {
            background-color: yellow
        }
    </style>
</head>

<body>
    <table>
        <th>The table header</th>
        <tr>
            <td>1</td>
            <td>2</td>
            <td>3</td>
            <td>4</td>
            <td>5</td>
        </tr>
        <tr>
            <td>1</td>
            <td>2</td>
            <td>3</td>
            <td>4</td>
            <td>5</td>
        </tr>
        <tr>
            <td>1</td>
            <td>2</td>
            <td>3</td>
            <td>4</td>
            <td>5</td>
        </tr>
    </table>
</body>

</html>
Copy the code

JS, algorithm related

1. Promise simulation implementation

2. Promise. All implementations

/ / promise. All implementations
// promise.all(iterable) returns a new promise instance.
// This example will become a big pity only if all the promises in iterable parameter are fulfilled or if the parameters do not include promises.
// This instance calls back to failed if there is a failed promise in the parameter rejected. The failed message is the return result of the first failed promise

Promise.all_ = function(promises) {
    return new Promise((resolve, reject) = > {
        // array.from () converts an iterable to an Array
        promises = Array.from(promises);
        if(promises.length===0) {
            resolve([]);
        } else {
            let result = [];
            let index = 0;
            for(let i=0; i<promises.length; i++) {
                // Consider that promise[I] may be either a Thenable object or a plain value
                Promise.resolve(promises[i]).then(data= > {
                    result[i] = data;
                    if(++index===promises.length) {
                        // All the promise states will be fulfilled, which is a big pity
                        resolve(result);
                    }
                }, err => {
                    reject(err);
                    return; })}}})}Copy the code

3. Promise. Race

// promise.race
// promise. race still returns a Promise in the same state as the first completed Promise;
// If the argument passed is non-iterable, an error will be thrown.

Promise.ra_ce = function(promises) {
    promises = Array.from(promises);
    return new Promise((resolve, reject) = > {
        if(promises.length===0) {
            return;
        } else {
            for(let i=0; i<promises.length; i++) {
                Promise.resolve(promises[i]).then(data= > {
                    resolve(data);
                    return;
                }, err => {
                    reject(err);
                    return; })}}})}Copy the code

4. The call

//
// Set the function as a property of the object
// Execute this function
// Delete this function
Function.prototype.call2 = function (context) {
    // Set the function to an object property and change this to point to (when null is passed, this points to window)
    context = context || window;
    context.fn = this;
    // Pass the parameter and execute the function, using an array to receive variable length arguments
    var args = [];
    for(var i = 1; i < arguments.length; i ++){
        args.push('arguments['+i+'] ');
    }
    var result = eval('context.fn(' + args + ') ');
    // Delete this function
    delete context.fn;
    return result;
}
Copy the code

5. Apply to realize

// Simulate the implementation of the apply() method

Function.prototype.apply2 = function(context,arr){
    context = context || window;
    context.fn = this;
    var result;
    if(! arr){ result = context.fn() }else{
        var args = [];
        for(var i = 0; i < arr.length; i++){
            args.push('arr[' + i + '] ')
        }
        result = eval('context.fn(' + args + ') ')}delete context.fn;
    return result;
}
Copy the code

6. The bind

// Simulate the implementation of BIND
// Bind () creates a new function. When the new function is called, the first argument to bind() will be this when it runs, and the subsequent sequence of arguments will be passed as its arguments before the arguments passed.
1. Return a function
// 2. You can pass in parameters
Note when passing parameters: a function can pass only one argument and then continue passing parameters when executing the returned function
// 3. Bind can use new to create objects, which is equivalent to using the original function as a constructor
// 4. An error is reported if bind is not called

Function.prototype.bind2 = function(context){
    if(typeof this! = ="function") {throw new Error("")}var self = this;
    var args = Array.prototype.slice.call(arguments.1);
    var fNOP = function(){}
    var fBound =  function(){
        var bindArgs = Array.prototype.slice.call(arguments);
        self.apply(self instanceof fNOP ? this : context,args.concat(bindArgs));
    }
    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();
    return fBound;
}

Copy the code

Inheritance method

// Constructor inheritance
function Person1(name) {
    this.name = name;
}

function Student1(name, age) {
    Person1.call(this, name);
    this.age = age;
}
var s1 = new Student1("xuhanlin");
console.log(s1.name);


// Prototype chain inheritance
function Person2() {
    this.name = "renyuan";
}

function Student2(age) {
    this.age = age;
}
Student2.prototype = new Person2();
var s2 = new Student2();
console.log(s2.name);

// Combinatorial inheritance
function Person3() {
    this.name = "renyuan";
}

function Student3() {
    Person3.call(this);
    this.age = "18";
}
Student3.prototype = new Person3();
var s3 = new Student3();
console.log(s3.name, s3.age);

Copy the code

8. Closure

// The closure implements the countdown
for(var i = 10; i > 0; i--){
    (function(i){
        setTimeout((a)= > {
        console.log(i); },10-i)*1000)
    })(i)
}
Copy the code

9. If you

function debounce(func,wait){
    var timeout;
    return function(){
        var context = this;
        var args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(function(){ func.apply(context,args); },wait); }}Copy the code

10. The throttle

// Use a timestamp
// When the event is triggered, we extract the current timestamp and subtract the previous timestamp (initially set to 0).
// If it is longer than the specified period, execute the function and update the timestamp to the current timestamp,
// If the value is smaller than the value, no execution is performed.
function throttle(func,wait){
    return function(){
        var context = this;
        var args = arguments;
        var previous = 0;
        var now = +new Date(a);if(now - previous > wait){ func.apply(context,args); previous = now; }}}// Set the timer
function throttle(func,wait){
    var timeout;
    return function(){
        var context = this;
        var args = arguments;
        if(! timeout){ timeout = setTimeout(function(){
              timeout = null; func.apply(context,args) },wait); }}}Copy the code

11. The new implementation

function create(Con, ... args) {
  let obj = {}
  Object.setPrototypeOf(obj, Con.prototype)
 // obj.__proto__ = con.prototype
  let result = Con.apply(obj, args)
  return result instanceof Object ? result : obj
}
Copy the code

12. Array deduplication

var array = [1.1.'1'];

// Method 1: indexOf()
// Create a new array, iterate over the original array, use indexOf to check if the original array already exists, push it if it does not exist
function unique(arr){
    var res = [];
    for(let item of arr){
        if(res.indexOf(item) === - 1){ res.push(item); }}return res;
}


// Sort by sort
function unique(arr){
    var res = [];
    var newArr = arr.sort();
    for(let i=0; i<newArr.length; i++){
        if(newArr[i] ! == newArr[i+1]){ res.push(newArr[i]); }}return res;
}

// Use the uniqueness of Set
function unique(arr){
    return Array.from(new Set(arr));
}

// Method 4: Map
function unique (arr) {
    const map = new Map(a)return arr.filter((a) = >! map.has(a) && map.set(a,1))}console.log(unique(array));

Copy the code

13. Array flattening

var arr = [1[2[3.4]]];

// Loop through the array, if it is still an array, recursively call the flat method
function flatten(arr) {
    var result = [];
    for (let i = 0; i < arr.length; i++) {
        if (Array.isArray(arr[i])) {
            result = result.concat(flatten(arr[i]));
        } else {
            result.push(arr[i])
        }
    }
    return result;
}

// This is an example of a new method
function flatten(arr) {
    return arr.reduce(function (pre, item) {
        return pre.concat(Array.isArray(item) ? flatten(item) : item)
    }, []);
}

// Method 2: toString(), which has the disadvantage of changing the type of the element, only works if the elements in the array are integers
function flatten(arr) {
    return arr.toString().split(",").map(function (item) {
        return+item; })}console.log(flatten(arr));
Copy the code

14. Curry

function sub_curry(fn) {
    var args = [].slice.call(arguments.1);
    return function() {
        return fn.apply(this, args.concat([].slice.call(arguments)));
    };
}

function curry(fn, length) {

    length = length || fn.length;

    var slice = Array.prototype.slice;

    return function() {
        if (arguments.length < length) {
            var combined = [fn].concat(slice.call(arguments));
            return curry(sub_curry.apply(this, combined), length - arguments.length);
        } else {
            return fn.apply(this.arguments); }}; }Copy the code

15. The array is out of order

// The array is out of order
// Iterate through the array of elements, and then swap the current element with the element at a random position later

function shuffle(arr) {
    for (let i = arr.length; i > 0; i--) {
        let j = Math.floor(Math.random() * i)
        let x = arr[i - 1];
        arr[i - 1] = arr[j];
        arr[j] = x;
    }
    return arr;
}

var arr = [1.2.3.4.5];
console.log(shuffle(arr))
Copy the code

16. Quicksort

// Quicksort
// Find a base number, smaller than the base number to the left, larger than the base number to the right
// Repeat this process for left and right intervals

var quickSort = function(arr){
    if(arr.length <= 1) {return arr;
    }
    const pivotIndex = Math.floor(arr.length / 2); // Index of any base number
    const pivot = arr.splice(pivotIndex,1) [0]; // find the corresponding base number
    const left = [];
    const right = [];
    for(let i=0; i<arr.length; i++){
        if(arr[i] < pivot){
            left.push(arr[i]);
        }else{ right.push(arr[i]); }}return quickSort(left).concat([pivot], quickSort(right));
}

const arr = [98.42.25.54.15.3.25.72.41.10.121];
console.log(quickSort(arr));
Copy the code

17. Bubble sort

// Bubble sort
// Compare two adjacent elements, if the previous one is larger than the next one, move back, after a round of comparison, the largest number to the last one
// Repeat this step

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

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

18. Light and dark copy

// Implement shallow copy
// Iterate over the object and place the attributes and their values in a new object
var shallowCopy = function(obj) {
    // Only objects are copied
    if (typeofobj ! = ='object') return;
    // Determine whether to create an array or object based on the type of obj
    var newObj = obj instanceof Array ? [] : {};
    // Iterate over obj and determine if it is obj's property to copy
    for (var key in obj) {
        if(obj.hasOwnProperty(key)) { newObj[key] = obj[key]; }}return newObj;
}


// Implement deep copy
// Determine the type of the property value before copying it. If it is an object, copy it recursively
var deepCopy = function(obj){
    if(typeof(obj) ! = ="object") return;
    var newObj = obj instanceof Array ? [] : {};
    for(let key in obj){
        if(obj.hasOwnProperty(key)){
            newObj[key] = typeof obj[key] === "object"? deepCopy(obj[key]) : obj[key]; }}return newObj;
}
Copy the code

19. Implement a summation function such as sum(1,2,3)(2).valueof ()

function sum(. args) {

let result = 0;

result = args.reduce(function (pre, item) {
  return pre + item;
}, 0);

let add = function (. args) {

  result = args.reduce(function (pre, item) {
    return pre + item;
  }, result);

  return add;
};

add.valueOf = function () {
  console.log(result);
}

return add;
}
Copy the code

20. Add large numbers

// implement a function that adds two large integers out of range
function bigNumberAdd(a,b){
    var res = ""; // Receive the result as a string
    var carry;  // Save the carry result
    // Convert a string to an array
    a = a.split("");
    b = b.split("");
    // End the loop when the array length is all 0 and no longer carries
    while(a.length || b.length || carry){
        carry += a.pop() + b.pop();
        res += carry % 10;
        True and false values are converted to 1 and 0 during addition
        carry = carry > 9;
    }
    return res;
}
Copy the code

21. Greatest common divisor, least common multiple

// Find the greatest common divisor of two numbers
// Toss and turn division
// Mod a small number with the remainder of a large number, mod a small number with the remainder of a small number, recursive until the remainder is zero
function getMaxCommonDivisor(a, b) {
    if (b === 0) {
        return a;
    }
    return getMaxCommonDivisor(b, a % b)
}

// Find the least common multiple
// Multiply two numbers and divide by their greatest common divisor

function getMinCommonMutiple(a, b) {
    return a * b / getMaxCommonDivisor(a, b);
}
Copy the code

22. Duplicate numbers in an array

// Method 3:
// Place the number in the corresponding index at the corresponding position. For example, if the first number is 2, place it at the index 2
// Put the number into the corresponding bucket
var findRepeatNumber = function(nums){
    for(let i=0; i<nums.length; i++){
        while(i ! == nums[i]){if(nums[i] == nums[nums[i]]){
                return nums[i];
            }else{
                vartemp = nums[i]; nums[i] = nums[temp]; nums[temp] = temp; }}}// return -1;
}
Copy the code

23. Rotate the smallest number in the array

/ / ideas:
// find the minimum value pass
// dichotomy:
// Because it is a rotated array, the preceding elements are greater than or equal to the following elements, and the smallest element is the boundary
// The pointer refers to the left (I) and right (j) ends and is compared with the middle number (index m)
// nums[m] > nums[j];
// nums[m] < nums[j];
// nums[m] === nums[j], j = j-1

var minArray = function (nums) {
    var i = 0;
    var j = nums.length - 1;
    while (i < j) {
        var m = Math.floor((i + j) / 2);
        if (numbers[m] > numbers[j]) {
            i = m + 1;
        } else if (numbers[m] < numbers[j]) {
            j = m;
        } else {
            j = j - 1; }}return numbers[i];
};
Copy the code

24. More than half of the numbers in the array

// Method 1:
// Use map to record the values in the array and the number of occurrences
var majorityElement = function(nums) {
    // write code here
const len = nums.length 
if (len === 0) return 0

const map = new Map(a)for (let i of nums) {
    if (map.get(i) === undefined) {
        map.set(i, 1)}else {
        map.set(i, map.get(i)+1)}}for (let item of map.entries()) {
    if (item[1] > Math.floor(len/2)) return item[0]}return 0
};

// Sort the array more than half the time, then the index in the array must be this number
var majorityElement = function(nums){
    var newNums = nums.sort();
    return newNums[Math.floor(nums.length / 2)];
};
Copy the code

25. Build product arrays

1. Left: array A is iterated forward
// 2. Right: reverse traversal array A, multiplicative
// 3. Left * right = B array

function constructArr(a) {
    var res = [];
    var left = 1;
    for (let i = 0; i < a.length; i++) {
        res[i] = left;
        left *= a[i];
    }
    var right = 1;
    for (let i = a.length - 1; i >= 0; i--) {
        res *= right;
        right *= a[i];
    }
    return res;
}
Copy the code

26. Maximum sum of continuous subarrays

var maxSubArray = function(nums){
    let max = -Infinity;
    nums.reduce((pre,cur) = > {
        if(pre > 0){
            pre += cur; // The sum of contiguous subarrays is greater than 0
        }else{
            pre = cur;  // The sum of contiguous subarrays is less than 0, plus it gets smaller and smaller
        }
        max = max > pre ? max : pre;
        return pre;
    },0)
    return max;
}
Copy the code