This week’s interview questions:

  • Implement the promise.race method
  • JSONP principle and simple implementation
  • Implement an array to remove the weight of the method
  • What are the methods to clear the float
  • Write a generic Currying function

More quality articles can be found at github.com/YvetteLau/B…

20. Implement the promise.race method

Before implementing the promise.race method, we first need to know the features and features of promise.race, because we can go further to write the implementation after we know the features and features of promise.race.

Promise. Race function

Promise. Race (iterable) returns a Promise, once in iterable a Promise state is fulfilled/rejected, This is a big pity/Promise. Race returns the Promise state which is fulfilled/Rejected.

let p = Promise.race([p1, p2, p3]);
Copy the code

If one instance of P1, P2, and P3 changes state first, then the state of P changes. The return value of the first changed Promise instance is passed to p’s callback.

Promise. The characteristics of the race

The return value of promise. race is a Promise instance

  • If the argument passed is an empty iterable, thenPromise.raceThe returnedpromiseIs alwayspending
  • If the parameter passed does not contain anypromise.Promise.raceA pending is returnedpromise
  • if可迭代Contains one or more nonpromiseValue or a promise that has been resolvedPromise.raceWill be resolved as a可迭代The first value found in.

The realization of the Promise. Race

Promise.race = function (promises) {
    // Promises pass in iterables. // Promises are promises.
    promises = Array.from(promises);// Convert an iterable to an array
    return new Promise((resolve, reject) = > {
        if (promises.length === 0) {
            // Empty iterable;
            // Used in pending state
        } else {
            for (let i = 0; i < promises.length; i++) {
                Promise.resolve(promises[i]).then((data) = > {
                    resolve(data);
                }).catch((reason) = >{ reject(reason); }}}})); }Copy the code

21. JSONP principle and simple implementation

Although browsers have the same origin policy, the SRC attribute of the

Implementation principle:

  • Step1: create the callback method
  • Step2: Insert the script label
  • Step3: The background receives the request, parses the callback method passed by the front end, returns the call of the method, and passes the data as parameter to the method
  • Step4: the front end performs the method call returned by the server

Jsonp source code implementation

function jsonp({url, params, callback}) {
    return new Promise((resolve, reject) = > {
        // Create the script tag
        let script = document.createElement('script');
        // Hang the callback function on the window
        window[callback] = function(data) {
            resolve(data);
            // Delete the inserted script tag after executing the code
            document.body.removeChild(script);
        }
        // The callback function is added to the request addressparams = {... params, callback}//wb=b&callback=show
        let arrs = [];
        for(let key in params) {
            arrs.push(`${key}=${params[key]}`);
        }
        script.src = `${url}?${arrs.join('&')}`;
        document.body.appendChild(script);
    });
}
Copy the code

Use:

function show(data) {
    console.log(data);
}
jsonp({
    url: 'http://localhost:3000/show'.params: {
        //code
    },
    callback: 'show'
}).then(data= > {
    console.log(data);
});
Copy the code

Server code (Node):

// Express starts a background service
let express = require('express');
let app = express();

app.get('/show', (req, res) => {
    let {callback} = req.query; // Get the name of the passed callback function. Callback is the key
    res.send(`${callback}('Hello! ') `);
});
app.listen(3000);
Copy the code

22. Implement an array de-weight method

Method 1: Use ES6 new data typesSet

A Set is similar to an array, but the values of its members are unique and have no duplicate values.

function uniq(arry) {
    return [...new Set(arry)];
}
Copy the code

Method 2: use ofindexOf

function uniq(arry) {
    var result = [];
    for (var i = 0; i < arry.length; i++) {
        if (result.indexOf(arry[i]) === - 1) {
            // If result does not contain arry[I], add it to array
            result.push(arry[i])
        }
    }
    return result;
}
Copy the code

Method 3: use ofincludes

function uniq(arry) {
    var result = [];
    for (var i = 0; i < arry.length; i++) {
        if(! result.includes(arry[i])) {// If result does not contain arry[I], add it to array
            result.push(arry[i])
        }
    }
    return result;
}
Copy the code

Method 4: Usereduce

function uniq(arry) {
    return arry.reduce((prev, cur) = > prev.includes(cur) ? prev : [...prev, cur], []);
}
Copy the code

Method 5: UseMap

function uniq(arry) {
    let map = new Map(a);let result = new Array(a);for (let i = 0; i < arry.length; i++) {
        if (map.has(arry[i])) {
            map.set(arry[i], true);
        } else {
            map.set(arry[i], false); result.push(arry[i]); }}return result;
}
Copy the code

23. What are the methods for clearing floats?

When the height of the container is auto and the contents of the container have floating elements (float is left or right), the height of the container cannot automatically grow to match the height of the content, causing the content to overflow out of the container and affecting (or even destroying) the layout. This phenomenon is called float overflow, and CSS processing to prevent this phenomenon is called CSS clear float.

<style>
    .inner {
        width: 100px;
        height: 100px;
        float: left;
    }
</style>
<div class='outer'>
    <div class='inner'></div>
    <div class='inner'></div>
    <div class='inner'></div>
</div>
Copy the code

1. The use ofclearattribute

Create an empty element inside

and set clear: both; Style.
  • Advantages: Simple, less code, good browser compatibility.
  • Cons: Need to add a lot of non-semantic HTML elements, code is not elegant, not easy to maintain later.

2. The use ofclearAttribute + pseudo-element

.outer:after{
    content: ' ';
    display: block;
    clear: both;
    visibility: hidden;
    height: 0;
}
Copy the code

After, if you want to support IE6 and ie7, you need to set the outer element to zoom: 1;

3. Use BFC layout rules

According to the RULES of the BFC, when calculating the height of the BFC, the floating element also participates in the calculation. To clear the float, you only need to trigger a BFC.

You can use the following methods to trigger the BFC

  • Position is absolute or fixed
  • Overflow is not a visible block element
  • Display: inline-block, table-cell, table-caption

Such as:

.outer {
    overflow: hidden;
}
Copy the code

Note that using display: inline-block produces a gap.

24. Write a generic Curried function

Before we begin, we need to understand the concept of currization of functions.

Function corrification is the technique of converting a function that takes multiple arguments into a function that takes a single argument (the first argument of the original function) and returns a new function that takes the remaining arguments and returns the result.

const currying = (fn, ... args) = >
    args.length < fn.length
        // If the length of the argument is insufficient, the function is re-currified and waits for the new argument to be accepted
        ? (.arguments) = >currying(fn, ... args, ... arguments)// If the parameter length is sufficient, the function is executed: fn(... args);Copy the code
function sumFn(a, b, c) {
    return a + b + c;
}
var sum = currying(sumFn);
console.log(sum(2) (3) (5));/ / 10
console.log(sum(2.3.5));/ / 10
console.log(sum(2) (3.5));/ / 10
console.log(sum(2.3) (5));/ / 10
Copy the code

The main functions of function Currization:

  • Parameters of reuse
  • Early return – Returns a new function that takes the remaining arguments and returns the result
  • Deferred execution – Returns a new function and waits for execution

Reference article:

[1] CSS- Clear float

[2] Kerritization of JS functions in detail

[3] JavaScript array deduplicating

Thank you for your precious time to read this article. If this article gives you some help or inspiration, please do not spare your praise and Star. Your praise is definitely the biggest motivation for me to move forward. Github.com/YvetteLau/B…

Pay attention to the public number, join the technical exchange group