Utils tool method library

Call method

export function call(Fn,obj,... args) { if(obj === undefined || obj === null) { obj = globalThis; } // add a temporary method to obj. Temp = Fn; Let result = obj.temp(... args); // delete obj.temp; Return result; }Copy the code

Call test case

function add(a,b) { console.log(this); return a + b + this.c; } let obj = { c:521 } window.c = 1; // let result = call(add,obj, 2); // console.log({result}); Let the result = call (add, null, 1, 2); console.log(result);Copy the code

The apply method

export function apply(Fn,obj,args) { if(obj === undefined || obj === null) { obj = globalThis; } // Add a temporary variable to obj. Temp = Fn; Let result = obj.temp(... args); // Delete the temporary attribute delete obj.temp; // return result; }Copy the code

Apply test cases

import { apply } from './apply'; function add(a,b) { console.log(this); return a + b + this.c; } let obj = { c:521 } window.c = 1; Let the result = the apply (add, null, [1, 2]). console.log(obj); console.log(result);Copy the code

The array concat

  • Var arr = concat(array,value1[])
  • Merge n arrays or values with the current array to generate a new array, leaving the original array unchanged
export function concat(array,... values) { const arr = [...array]; values.forEach(value => { if(Array.isArray(value)) { arr.push(... value) }else { arr.push(value) } }); return arr; }Copy the code

Array stroke flatten method

  • Let array = [1,[2,[3,[4,[5]],]]
  • Function: Take all elements of a nested array (multidimensional) and put them into a new array (one-dimensional)
import { concat } from './concat' export function flatten1(array) { return array.reduce((pre,item) => { if(Array.isArray(item)) { pre = concat(pre,flatten1(item)); }else { pre.push(item); } return pre; }}, [])Copy the code
export function flatten2(array) { let arr = []; arr = concat([],... array); while(arr.some(item => Array.isArray(item))) { arr = concat([],... arr) } return arr; }Copy the code

The map method of an array

  • Returns a new array
export function map(array,callback) { const arr = []; for(let i=0; i < array.length; i++) { let result = callback(array[i],i); arr.push(result); } return arr; }Copy the code

Array reduce method

  • Returns a cumulative result
export function reduce(array,callback,initValue) { let total = initValue; for(let i = 0; i < array.length; i++) { total = callback(total,array[i],i); } return total; }Copy the code
  • Reduce the usage of the
Let array = [1, 2, 3, 4, 5]; let res = utils.reduce(array,(total,item,index) =>{ return total + item },0);Copy the code

Array filter method

  • Filter array
export function filter(array,callback) { const arr = []; for(let i=0; i < array.length; i++) { let bool = callback(array[i],i); if(bool) { arr.push(array[i]); } } return arr; }Copy the code
  • Filter Usage
Let array = [1, 2, 3, 4, 5]; let res = utils.filter(array,(item,index) => { return item > 2 });Copy the code

The findIndex method of an array

  • Finds the index of an element in an array
export function findIndex(array,callback) { let index = -1; for(let i=0; i < array.length; i++) { let item = array[i] let bool = callback(item,i); if(bool) { index = i } } return index; }Copy the code
  • Method of use
Let array = [1, 2, 3, 4, 5]; let res = utils.findIndex(array,(item,index) => { return item === 2 }); console.log('res',res);Copy the code

The use of the every method of arrays

  • Return true only if all of the array returns true
export function every(array,callback) { for(let i=0; i < array.length; i++) { let bool = callback(array[i],i); if(! bool) return false } return true; }Copy the code
  • Method of use
Let array = [1, 2, 3, 4, 5]; let res = utils.every(array,(item,index) => { return item >= 1 }); console.log('res',res);Copy the code

The use of some methods in arrays

  • Returns true as long as one of the arrays returns true
export function some(array,callback) { let bool = false; for(let i=0; i < array.length; i++) { bool = callback(array[i],i); if(bool) return true; } return bool; }Copy the code

The compact method of arrays

  • Overriding all methods in an array that return true
export function compact(array) { let arr = []; for(let i=0; i < array.length; i++) { if(!! array[i]) arr.push(array[i]); } return arr; }Copy the code
  • Method of use
let array = [1,undefined,3,false,5,'0'];
let res = utils.compact(array);
Copy the code

Thunk method of an array

  • A one-dimensional array generates a two-level array of the specified size
export function chunk(array,size) { let bigArr = []; let smallArr = []; if(size === 0 || size > array.length || size === undefined){ size = array.length; } if(size < 0) { size = 1; } for(let i=0; i < array.length; i++) { if(smallArr.length === 1) { bigArr.push(smallArr); } if(smallArr.length === size) { smallArr = []; } smallArr.push(array[i]); } return bigArr; }Copy the code
  • Method of use
Let array = [6]; let res = utils.chunk(array,4);Copy the code

Array difference method

  • Find a subset of a collection
export function difference(array1,array2) { const arr = []; if(array1.length === 0) { return arr; }else if(array2.length === 0) { return [...array1]; } for(let i=0; i < array1.length; i++) { if(array2.indexOf(array1[i]) === -1) { arr.push(array1[i]); } } return arr; }Copy the code
  • Method of use
Let array = hc-positie [1]; Let array1 = [5]; let res = utils.difference(array,array1);Copy the code

Array merge method

  • Merge n arrays to merge and deduplicate
export function mergeArray(array1,array2) { if(array1.length === 0) { return [...array2]; }else if(array2.length === 0) { return [...array1] } let arr = [...array1]; for(let i=0; i < array2.length; i++) { if(array1.indexOf(array2[i]) === -1) { arr.push(array2[i]); } } return arr; }Copy the code
  • Method of use
Let array1 =,3,5,7,5 [1]; Let array2 =,5,8 [1]; let res = utils.mergeArray(array1,array2);Copy the code
  • Supports merging of multiple arrays
export function mergeArray1(array1,... arrays) { if(arrays.length === 0) { return [...array1]; } let arr = [...array1]; let newArrays = []; for(let i=0; i < arrays.length; i++) { for(let j=0; j < arrays[i].length; j++) { newArrays.push(arrays[i][j]); } } let setArr = [...new Set(newArrays)]; for(let i=0; i < setArr.length; i++) { if(array1.indexOf(setArr[i])=== -1) { arr.push(setArr[i]); } } return arr; }Copy the code
  • Method of use
Let array1 =,3,5,7,5 [1]; Let array2 =,5,8 [1]; Let array3 = Sherwin [4]; Let array4 =,4,6,8,10 [2]; let res = utils.mergeArray1(array1,array2,array3,array4);Copy the code

Pull method of array

  • Pull removes elements in the array that are the same as value and returns all deleted elements
export function pull(array,... values) { const arr = []; for(let index = 0; index < array.length; index++) { const item = array[index]; if(values.indexOf(item) ! == -1) { array.splice(index,1); arr.push(item); index-- } } return arr; }Copy the code
  • The test method
Let arr =,3,5,3,7 [1]; Let res = utils. Pull (arr, 2,7,3,7); console.log('res',res);Copy the code

Array drop method

export function drop(array,count) { if(array.length === 0) return []; if(count===undefined || count <= 0 || count === null) { count = 1; } let arr = []; for(let i=0; i < array.length; i++) { if(i >= count) { arr.push(array[i]); } } return arr; }Copy the code
Export function dropRight(array,count) {if(array.length === 0) return []; // Export function dropRight(array,count) {if(array.length === 0) return []; if(count === undefined || count === null || count <=0) { count = 1 } let arr = []; for(let i=0; i < array.length; i++) { if(i < count) { arr.push(array[i]) } } return arr; }Copy the code
  • Method of use
Let arr = hc-positie [1]; let res = utils.dropRight(arr,2); console.log('res',res)Copy the code

A shallow copy of the object

export function clone1(target) {
    if(target instanceof Array) {
        return Array.from(target)
    }else if(target !== null && typeof target === 'object') {
        return Object.assign({},target);
    }else {
        return target;
    }
}
Copy the code
/ / the second mode of implementing the export function clone2 (target) {if (target instanceof Array | | (target! == null && typeof target === 'object')) { let cloneTarget = target instanceof Array ? [] : {}; for(let key in target) { if(target.hasOwnProperty(key)) { cloneTarget[key] = target[key]; } } return cloneTarget; }else { return target; }}Copy the code

The deep cobb of the image

export function deepClone(target,map = new Map()) {
  if(target instanceof Array || (target !== null && typeof target === 'object')) {
    let cloneTarget = map.get(target);
    if(cloneTarget) {
        return cloneTarget;
    }
    if(target instanceof Array) {
        cloneTarget = [];
        map.set(target,cloneTarget);
        target.forEach((item,index) => {
            cloneTarget[index] = deepClone(item,map);
        })
    }else {
        cloneTarget = {};
        map.set(target,cloneTarget);
        for(let key in target) {
            if(target.hasOwnProperty(key)) {
                cloneTarget[key] = deepClone(target[key],map)
            }
        }
    }
    return cloneTarget;
  } else {
      return target;
  }
}
Copy the code
  • Method of use
let obj = {
    a:1,
    b:['e','f','g'],
    c:{h:{i:2}},
    d:function() {

        }
}       
let deepObj = utils.deepClone(obj);
console.log(deepObj,deepObj.c === obj.c);
Copy the code

ReverseString is a string in reverse order

export function reverseString(str) { if(typeof str ! =='string') return str; let arr = []; for(let i = str.length; i >=0; i--) { arr.push(str[i]); } return arr.join(''); }Copy the code
  • Method of use
let res = utils.reverseString('abcd');
Copy the code

Whether the string is palindrome

export function palindrome(str) { if(typeof str ! == 'string') return str; let arr = []; for(let i= str.length; i >=0; i--) { arr.push(str[i]); } return str === arr.join(''); }Copy the code
  • Method of use
let res = utils.palindrome('abcba');
Copy the code

String out with…

export function truncate(str,count) { if(typeof str ! == 'string') return str; return str.length > count ? `${str.substring(0,count)}... `:str; }Copy the code
  • Method of use
let res = utils.truncate('boomerang',7);
Copy the code

Github Address Num Packet address