These days, I saw a big junior interviewing bytedance mosquito, and suddenly I felt that I was too hot… I didn’t know more than half of the college entrance exam questions… I quickly dive into learning to improve myself, while digging gold and Googling. Simple implementation of several commonly used functions…… (borrowed from too many people’s article…… confused…… can not write reference……
Deep copy deepClone
function deepClone(target, hash = new WeakMap()) {
// It is not an object or null
if (typeoftarget ! = ="object" || target == null) return target;
// Check whether there is an object reference through WeakMap
if (hash.has(target)) return hash.get(target);
// Check whether it is an array or a string
const result = target instanceof Array ? [] : {};
// Put the result into WeakMap, where key is target and value is result
hash.set(target, result);
// for in
for (const key in target) {
// Avoid properties on the prototype chain
if (Object.prototype.hasOwnProperty.apply(target,key)) {
// recursive callresult[key] = _deepClone(target[key]); }}// Return the result
return result;
}
Copy the code
Stabilization debounce
function debounce(handler, wait = 300, immediate = false) {
// Declare a variable timer
let timer;
// Check whether the parameters meet expectations
if (typeofhandler ! = ="function") throw new TypeError("The first params shoule be a Function");
if (typeofwait ! = ="number") throw new TypeError("The second params shoule be a Number");
return function() {
// Cache context and parameters
const context = this,
args = [...arguments];
// Clear the timer if it exists
timer && clearTimeout(timer);
if (immediate) {
// If immediate is true and the timer does not exist, set the timer and set the timer to null after the specified time
constcallNow = ! timer; timer = setTimeout((a)= > {
timer = null;
}, wait);
// The handler is executed immediately, binding the context and passing the parameters through apply
callNow && handler.apply(context, args);
} else {
// If immediate is false, set the timer
timer = setTimeout((a)= >{ handler.apply(context, args); }, wait); }}; }Copy the code
Throttling throttle
function throttle(handler, wait = 300) {
// Declare a variable timer
let timer;
return function() {
// If the timer exists, it returns the same value
if (timer) return;
// Cache context and parameters
const context = this,
args = [...arguments];
// Set the timer
timer = setTimeout((a)= > {
// Execute handler, binding the context and passing the parameters through apply
handler.apply(context, args);
// Timer is set to null
timer = null;
}, wait);
};
}
Copy the code
Is it a pure object isPlainObject
function isPlainObject(obj) {
return Object.prototype.toString.call(obj) === "[object Object]";
}
Copy the code
Depth contrast isEqual
function isEqual(target1, target2) {
// return the same value
if (target1 === target2) return true;
const isPlainObject = obj= > Object.prototype.toString.call(obj) === "[object Object]";
// If either object is not pure, the comparison result is returned directly
if(! isPlainObject(target1) || ! isPlainObject(target2))return target1 === target2;
// Get an array of two keys
const target1Keys = Object.keys(target1);
const target2Keys = Object.keys(target2);
if(target1Keys.length ! == target2Keys.length)return false;
// Iterate over target1, recursively calling isEqual to compare each item, and return false if any item is different
for (const key in target1) {
if (target1.hasOwnProperty(key)) {
if(! isEqual(target1[key], target2[key]))return false; }}/ / all the same
return true;
}
Copy the code
Flatten array
function flatArray(arr, depth = Infinity) {
// If it is not an array, an error is reported
if(! arrinstanceof Array) throw new TypeError("Expect Array");
// Check whether the FLAT method of ES10 is supported
if (Array.prototype.flat) {
// Support calls directly
return arr.flat(depth);
} else {
// See if all the elements in the array are normal types
const isDeep = arr.some(item= > Array.isArray(item));
// If both types are normal, return them directly
if(! isDeep)return arr;
// Flat the first layer of the array with the array concat method
constresult = [].concat(... arr);// Recursive call, flat the deep array
returnflatArray(result); }}Copy the code
Array quickSort
function quickSort(target) {
// It is not an array or the array length is less than 2
if (Object.prototype.toString.apply(target) ! = ='[object Array]' || target.length < 2) return target
// Copy a number of copies
const _arr = [...target]
// Find and fetch the base element
const pivotItem = _arr.splice(Math.floor(_arr.length / 2), 1)
// Define two temporary arrays to store elements smaller than and larger than the base
const smallerArr = []
const biggerArr = []
// Go through the number group and classify the elements
for (let index = 0; index < _arr.length; index++) {
const element = _arr[index]
pivotItem > element ? smallerArr.push(element) : biggerArr.push(element)
}
// Call two temporary arrays recursively and merge the two arrays with the base element
const result = this._quickSort(smallerArr).concat(pivotItem, this._quickSort(biggerArr))
// Returns a new array
return result
},
Copy the code
Array bubbleSort bubbleSort
function bubbleSort(target) {
// It is not an array or the array length is less than 2
if (Object.prototype.toString.apply(target) ! = ='[object Array]' || target.length < 2) return target
// Copy a number of copies
const _arr = [...target]
// go through the number group
for (let index = 0; index < _arr.length; index++) {
for (let innerIdx = index + 1; innerIdx < _arr.length; innerIdx++) {
// Compare adjacent elements in pairs, swap elements, swap large elements behind
if (_arr[index] > _arr[innerIdx]) {
[_arr[index], _arr[innerIdx]] = [_arr[innerIdx], _arr[index]]
}
}
}
// Returns a new array
return _arr
}
Copy the code