leetcode — JavaScript Topics (7): Simplify objects, execute cancelable deferred functions, execute asynchronous functions in parallel, merge two arrays according to ID, add two Promise objects, sorting methods

Column statement: Just use the simplest and easy-to-understand method to pass, don't seek optimization, don't spray if you don't like it

2705. Thin Objects

Title

Now given an object or array obj, returns a compact object. A compact object is the same as the original object, except that the keys containing false values ​​are removed. The operation applies to the object and its nested objects. Arrays are treated as objects with indices as keys. When Boolean(value) returns false, the value is considered false.
You can assume obj is the output of JSON.parse. In other words, it's valid JSON.

Knowledge points:

Depth-first traversal

train of thought

Typical classification judgment + recursive questions, there have been many before, we pass in an object or an array, so we first need to use Array.isArray to determine whether it is an array or an object:

  • If it's an array, we iterate over each item in it, and if it's not false, put it in the returned array.
  • If it is an object, we recurse each key in it, and if it is not false, we put this key-value pair into the returned object.
    Because when we recurse, we will pass in values ​​that are not arrays and objects, so we judge that if the value passed in is not object type or null (because null will also be judged as object type), we will return directly (its judgment will be processed in the previous level)
the code
var compactObject = function(obj) {
    
    

    if (obj == null || typeof obj !== 'object') {
    
    
        return obj;
    }
    if (Array.isArray(obj)) {
    
    
        const res = [];
        for (let it of obj) {
    
    
            const val = compactObject(it);
            if (val) res.push(val);
        }
        return res;
    }
    const res = {
    
    };
    const keys = Object.keys(obj);
    for (let key of keys) {
    
    
        const val = compactObject(obj[key]);
        if (val) res[key] = val;
    }
    return res;
};

2715. Execute cancelable deferred functions

Title

Given a function fn, an array of parameters args and a timeout t in milliseconds, return a cancel function cancelFn.
After a delay of t milliseconds, fn shall be called with args unless cancelFn is called first. And in this case, fn should not be called.

Knowledge points:

counter, closure

train of thought

A very simple application of closure, create a timer, execute the required execution function after a certain delay, and return a function to cancel it, this function clears the timer, because of the characteristics of the closure, we can use this function to access the timer created in the function.

the code
/**
 * @param {Function} fn
 * @param {Array} args
 * @param {number} t
 * @return {Function}
 */
var cancellable = function(fn, args, t) {
    
    
    let timer = setTimeout(() => {
    
    
        fn(...args)
    },t)
    return () => {
    
     clearTimeout(timer) };
};

2721. Execute asynchronous functions in parallel

Title

This question is also the author's Bytedance interview handwritten question (implement a promise.all)
Given an array of asynchronous functions functions, return a new promise object promise. Each function in the array takes no arguments and returns a promise.
promise resolve condition:
when all promises returned from functions resolve successfully. The resolved value of promise should be an array of resolved values ​​of promises in the order they appear in functions.
promise reject condition:
when any promise returned from functions is rejected. Promises are also rejected, and the reason for the first rejection is returned.
Please solve without using the built-in Promise.all function.

Knowledge points:

promise、promise.all

train of thought

Implement a promise.all, this function api will return after all the incoming promises are completed, we first create a new promise as the return value, the successful return of this promise is after all the incoming promises are executed, and the failure return is in After a promise fails.
We use a now to record how many executions have been executed, and then traverse the incoming array. For each promise, after it is executed, put the corresponding return value in the returned array execution position, and then let now + 1.
If the length of now is the same as that of the input array at this time, it means that the execution is completed, and the array recording all return values ​​is returned as success.
If any of the incoming promises fails, we simply fail with the error message for the failed promise.

the code
/**
 * @param {Array<Function>} functions
 * @return {Promise<any>}
 */
var promiseAll = async function (functions) {
    
    
    let now = 0;
    let re = new Array(functions.length);
    return new Promise((res, rej) => {
    
    
        for (let i = 0; i < functions.length; i++) {
    
    
            functions[i]().then((data) => {
    
    
                now++;
                re[i] = data
                if (now == functions.length) {
    
    
                    res(re);
                }
            },(err) => {
    
    
                rej(err);
            })
        }
    })
};
/**
 * const promise = promiseAll([() => new Promise(res => res(42))])
 * promise.then(console.log); // [42]
 */

2722. Merge two arrays by ID

Title

Given two arrays arr1 and arr2, return a new array joinedArray. Each object in the two input arrays contains an id field. joinedArray is an array formed by joining arr1 and arr2 by id. The length of joinedArray should be the length of the unique value id. The returned array should be sorted by id in ascending order.
If an id exists in one array but not in the other, the object should be included in the resulting array without modification.
If two objects share an id, their properties should be merged:
if a key exists in only one object, that key-value pair should be contained in the object.
If a key is contained in both objects, the value in arr2 shall override the value in arr1.

Knowledge points:

merge sort, object merge

train of thought

The idea of ​​​​double pointers, we first sort the two arrays according to the size of the id, and then merge them from the first position of the two arrays:

  • If the element id pointed to by the two pointers is the same, then this element needs to be merged and implemented using Object.assign. The logic of this function is: if a key only exists in one object, then the key-value pair should be included in the object, If a key is contained in both objects, the value in arr2 should override the value in arr1, which is the requirement of the title.
  • If the pointed ids are different, we put the one with the smaller id into the result and continue our traversal
  • When any array traversal ends, we put the remaining elements in an array into the result array
the code
/**
 * @param {Array} arr1
 * @param {Array} arr2
 * @return {Array}
 */
var join = function (arr1, arr2) {
    
    
    arr1.sort((a, b) => a.id - b.id);
    arr2.sort((a, b) => a.id - b.id);
    let res = [];
    let j = 0;
    for (var i = 0; i < arr1.length; i++) {
    
    
        if (j == arr2.length) {
    
    
            break;
        }
        let id1 = arr1[i].id;
        if (arr2[j].id == id1) {
    
    
            res.push(Object.assign(arr1[i], arr2[j]));
            j++;
        } else if (arr2[j].id < id1) {
    
    
            res.push(arr2[j]);
            j++;
            i--;
        } else {
    
    
            res.push(arr1[i]);
        }
    }
    while (i < arr1.length) {
    
    
        res.push(arr1[i]);
        i++;
    }
    while (j < arr2.length) {
    
    
        res.push(arr2[j]);
        j++;
    }
    return res.sort((a, b) => a.id - b.id);
};

2723. Add two Promise objects

Title

Given two promise objects promise1 and promise2, return a new promise. Both promise1 and promise2 will resolve to a number. The returned Promise should resolve to the sum of these two numbers.

Knowledge points:

promise

train of thought

Examine the basic concepts of promises. Use promise.then to wait for two promises to return. You need to process a promise after a promise returns, or use promise.all to process them. After the return values ​​​​of both promises are obtained, add them and return them as a new one. The successful return of the promise is enough

the code
/**
 * @param {Promise} promise1
 * @param {Promise} promise2
 * @return {Promise}
 */
var addTwoPromises = async function(promise1, promise2) {
    
    
    return new Promise((res,rej) => {
    
    

        promise1.then((res1) => {
    
    
            promise2.then((res2) => {
    
    
                res(res1 + res2)
            })
        }) 
    })
};

/**
 * addTwoPromises(Promise.resolve(2), Promise.resolve(2))
 *   .then(console.log); // 4
 */

2724. Sort By

Title

Given an array arr and a function fn, return a sorted array sortedArr. You can assume that fn returns only numbers, and that these numbers determine the sort order of sortedArr. sortedArr must be sorted in ascending order by the output values ​​of fn.

You can assume that for a given array, fn will not return duplicate numbers.

Knowledge points:

sort

train of thought

Simple question... Examine the use of the sort api, it passes in two values, you can process these two values, and then perform comparison logic

the code
/**
 * @param {Array} arr
 * @param {Function} fn
 * @return {Array}
 */
var sortBy = function (arr, fn) {
    
    
   return arr.sort((a, b) => fn(a) - fn(b));
};

Guess you like

Origin blog.csdn.net/weixin_46463785/article/details/131140663