The big guy said: "If you don't want to work overtime, you can memorize these 10 JS tricks"

In order to make the code I write more elegant and efficient, I deliberately asked the big guys about these 10 JS skills

1. Array partition

const listChunk = (list = [], chunkSize = 1) => {
    const result = [];
    const tmp = [...list];
    if (!Array.isArray(list) || !Number.isInteger(chunkSize) || chunkSize <= 0) {
        return result;
    };
    while (tmp.length) {
        result.push(tmp.splice(0, chunkSize));
    };
    return result;
};
listChunk(['a', 'b', 'c', 'd', 'e', 'f', 'g']);
// [['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['g']]

listChunk(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 3);
// [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]

listChunk(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 0);
// []

listChunk(['a', 'b', 'c', 'd', 'e', 'f', 'g'], -1);
// []

2. Find the intersection of array elements

const listIntersection = (firstList, ...args) => {
    if (!Array.isArray(firstList) || !args.length) {
        return firstList;
    }
    return firstList.filter(item => args.every(list => list.includes(item)));
};
listIntersection([1, 2], [3, 4]);
// []

listIntersection([2, 2], [3, 4]);
// []

listIntersection([3, 2], [3, 4]);
// [3]

listIntersection([3, 4], [3, 4]);
// [3, 4]

3. Press the icon to regroup the array

const zip = (firstList, ...args) => {
    if (!Array.isArray(firstList) || !args.length) {
        return firstList
    };
    return firstList.map((value, index) => {
        const newArgs = args.map(arg => arg[index]).filter(arg => arg !== undefined);
        const newList = [value, ...newArgs];
        return newList;
    });
};
zip(['a', 'b'], [1, 2], [true, false]);
// [['a', 1, true], ['b', 2, false]]

zip(['a', 'b', 'c'], [1, 2], [true, false]);
// [['a', 1, true], ['b', 2, false], ['c']]

4. Press the index to combine the array as an object

const zipObject = (keys, values = {}) => {
    const emptyObject = Object.create({});
    if (!Array.isArray(keys)) {
        return emptyObject;
    };
    return keys.reduce((acc, cur, index) => {
        acc[cur] = values[index];
        return acc;
    }, emptyObject);
};
zipObject(['a', 'b'], [1, 2])
// { a: 1, b: 2 }
zipObject(['a', 'b'])
// { a: undefined, b: undefined }

5. Check the value of the object property

const checkValue = (obj = {}, objRule = {}) => {
    const isObject = obj => {
        return Object.prototype.toString.call(obj) === '[object Object]';
    };
    if (!isObject(obj) || !isObject(objRule)) {
        return false;
    }
    return Object.keys(objRule).every(key => objRule[key](obj[key]));
};

const object = { a: 1, b: 2 };

checkValue(object, {
    b: n => n > 1,
})
// true

checkValue(object, {
    b: n => n > 2,
})
// false

6. Get object properties

const get = (obj, path, defaultValue) => {
    if (!path) {
        return;
    };
    const pathGroup = Array.isArray(path) ? path : path.match(/([^[.\]])+/g);
    return pathGroup.reduce((prevObj, curKey) => prevObj && prevObj[curKey], obj) || defaultValue;
};

const obj1 = { a: { b: 2 } }
const obj2 = { a: [{ bar: { c: 3 } }] }

get(obj1, 'a.b')
// 2
get(obj2, 'a[0].bar.c')
// 3
get(obj2, ['a', '0', 'bar', 'c'])
// 2
get(obj1, 'a.bar.c', 'default')
// default
get(obj1, 'a.bar.c', 'default')
// default

7. Convert special symbols to font symbols

const escape = str => {
    const isString = str => {
        return Object.prototype.toString.call(str) === '[string Object]';
    };
    if (!isString(str)) {
        return str;
    }
    return (str.replace(/&/g, '&amp;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#x27;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/\//g, '&#x2F;')
      .replace(/\\/g, '&#x5C;')
      .replace(/`/g, '&#96;'));
};

8. Use annotations to create an event listener

class EventEmitter {
    #eventTarget;
    constructor(content = '') {
        const comment = document.createComment(content);
        document.documentElement.appendChild(comment);
        this.#eventTarget = comment;
    }
    on(type, listener) {
        this.#eventTarget.addEventListener(type, listener);
    }
    off(type, listener) {
        this.#eventTarget.removeEventListener(type, listener);
    }
    once(type, listener) {
        this.#eventTarget.addEventListener(type, listener, { once: true });
    }
    emit(type, detail) {
        const dispatchEvent = new CustomEvent(type, { detail });
        this.#eventTarget.dispatchEvent(dispatchEvent);
    }
};

const emmiter = new EventEmitter();
emmiter.on('biy', () => {
    console.log('hello world');
});
emmiter.emit('biu');
// hello world

9. Generate a random string

const genRandomStr = (len = 1) => {
    let result = '';
    for (let i = 0; i < len; ++i) {
        result += Math.random().toString(36).substr(2)
    }
    return result.substr(0, len);
}
genRandomStr(3)
// u2d
genRandomStr()
// y
genRandomStr(10)
// qdueun65jb

10. Determine whether it is the specified hash value

const isHash = (type = '', str = '') => {
    const isString = str => {
        return Object.prototype.toString.call(str) === '[string Object]';
    };
    if (!isString(type) || !isString(str)) {
        return str;
    };
    const algorithms = {
        md5: 32,
        md4: 32,
        sha1: 40,
        sha256: 64,
        sha384: 96,
        sha512: 128,
        ripemd128: 32,
        ripemd160: 40,
        tiger128: 32,
        tiger160: 40,
        tiger192: 48,
        crc32: 8,
        crc32b: 8,
    };
    const hash = new RegExp(`^[a-fA-F0-9]{${algorithms[type]}}$`);
    return hash.test(str);
};

isHash('md5', 'd94f3f016ae679c3008de268209132f2');
// true
isHash('md5', 'q94375dj93458w34');
// false

isHash('sha1', '3ca25ae354e192b26879f651a51d92aa8a34d8d3');
// true
isHash('sha1', 'KYT0bf1c35032a71a14c2f719e5a14c1');
// false

Summary of front-end interview questions

The front-end interview questions are the interview questions I encountered during the interview. I will review and summarize after each interview. I have done a sorting, and found a professional answer in the technical blog, you can refer to the following:

Due to limited space, only part of the interview questions can be shared. The full version of the interview questions and answers can be read and downloaded by [click me] ~ Share with you for free

Guess you like

Origin blog.csdn.net/hugo233/article/details/114447408