JS Coding 技巧!!

1,179 阅读10分钟

防抖函数

触发函数后n秒之后执行回调函数,n秒之内如果再次被触发,则重新计时。

参数:

  1. fun:执行的回调函数。
  2. [time=1000]: 抖动时间。 返回: (Function):返回新的抖动函数。

例子:

const transfer = debounce(()=>{
    // TO DO
}, 2000);
// 正常调用
transfer()
源码
function debounce(fun, time=1000){
          let timer = undefined;
          return function(...args){
            if(timer){
                clearTimeout(timer)
            }
            time = setTimeout(()=>{
                timer = undefined;
                fun.apply(this,args)
            },time)
          }
      }

节流函数

在规定时间内只能执行一次回调函数

参数:

  1. fun:执行的回调函数。
  2. [time=1000]: 节流时间。

返回: (Function): 返回新的节流函数。

例子:

const transfer = throttle(()=>{
// TO DO
},2000);
// 调用
transfer();
源码
function throttle(fun, time = 1000) {
        let timer = undefined;
        return function (...args) {
          if (timer) {
            return;
          }
          timer = setTimeout(() => {
            fun.apply(this, args);
            timer = undefined;
          }, time);
        };
      }

随机数函数

返回符合范围内的随机数

参数:

  1. start:开始的范围(包含)。
  2. end: 结束的范围(不包含)。

返回: (Number): 返回符合范围的随机数。

例子:

randomNumber(1,10); // 9
源码
const randomNumber = (start, end) =>
        Math.floor(Math.random() * (end - start)) + start;

数组去重

删除数组重复的数据

参数:

  1. arr:想要去重的一维数组。

返回: (Array): 返回去掉重复数据的新数组。

例子:

// 使用
deDuplication([1,1,2]); // [1,2]
unique([1,2,1]); // [1,2]
源码
// Set 去重
const deDuplication = (arr=[])=>Array.from(new Set(arr));

// reduce 去重
const unique = (arr = []) => {
        if (!arr || arr.length === 0) {
          return [];
        }
        const uniqueArr = arr.reduce(
          (unArr, current) =>
            unArr.includes(current) ? unArr : unArr.concat(current),
          []
        );
        return uniqueArr
      };

Object[]去重

根据指定的对象属性Key,删除数组中对象属性值重复的数据

参数:

  1. arr:想要去重的一维数组。
  2. unKey: 对象的属性

返回: (Array): 返回去掉重复数据的新数组。

例子:

// 使用
const data = [{id:1,name:'qwe'},{id:1,name:'rty'}];
// 第一种
uniqueArrObj(data,'id'); // [{id:1,name:'qwe'}]

// 第二种
uniqueArrObj(data,'id'); // [{id:1,name:'qwe'}]
源码
// reduce 去重
const uniqueArrObj = (arr=[],unKey='')=>{
        const uniqueArr = arr.reduce((unArr, current)=>{
          const keyValue = unArr.map(item=>item[unKey]);
          return keyValue.includes(current[unKey]) ? unArr: [...unArr,current];
        },[])
        return uniqueArr;
      }
      
// filter 去重 效果更好
const uniqueArrObj = (arr, key) => {
      const keyMap = new Map();
      return arr.filter(item => !keyMap.has(item[key]) && keyMap.set(item[key], 1))
    }

重组树结构

根据parentId将一维数组结构重组为树结构

参数:

  1. treeArr: 原始的具有parentId的一维数组数据。
  2. id: 每个item对象的唯一id。
  3. [link = 'parentId']: 存储parentId值的属性名称。
  4. [idName = 'key']: 存储id值的属性名称。

返回: (Array): 重组完成的树形结构数组。

例子:

const treeData = [
        { id: 1, parent_id: null },
        { id: 2, parent_id: 1 },
        { id: 3, parent_id: 1 },
        { id: 4, parent_id: 2 },
        { id: 5, parent_id: 4 },
      ];
 // 第一种实现
 reorganizeTree(treeData,null,'parent_id','id');
 
 // 第二种实现
 reorganizeTree(treeData,'id','parent_id');
源码
const reorganizeTree = (
        treeArr = [],
        id = null,
        link = "parentId",
        idName = "key"
      ) =>
        treeArr
          .filter((itemF) => itemF[link] === id)
          .map((itemM) => ({
            ...itemM,
            children: reorganizeTree(treeArr, itemM[idName], link, idName),
          }));
          
 // 第二种实现方式
 
 const reorganizeTree = (flatArr, sonKey = 'id', parentKey = 'parent_id') => {
      const result = [];
      const idMap = {};
      for (const item of flatArr) {
        const {
          [sonKey]: sonId, [parentKey]: parentId
        } = item;
        if (!idMap[sonId]) {
          idMap[sonId] = {
            children: []
          }
        }
        idMap[sonId] = {
          ...item,
          children: idMap[sonId].children
        }
        const treeItem = idMap[sonId];
        if (!parentId) {
          // 为 0 null undefined '' 进入 证明这条数据为顶级的父节点
          result.push(treeItem);
        } else {
          if (!idMap[parentId]) {
            idMap[parentId] = {
              children: []
            }
          }
          idMap[parentId].children.push(treeItem)
        }
      }
      return result
    }

扁平化树型结构

将树结构数据转化为一维数组

参数:

  1. treeData: 原始树形结构数据。

返回: (Array): 扁平化为一维数组。

例子:

const list = [
        {
          id: 1,
          parent_id: null,
          children: [
            {
              id: 2,
              parent_id: 1,
              children: [
                {
                  id: 4,
                  parent_id: 2,
                  children: [{ id: 5, parent_id: 4, children: [] }],
                },
              ],
            },
            { id: 3, parent_id: 1, children: [] },
          ],
        },
      ];
flatTree(list); 
// 结果
[
    {
        "id": 1,
        "parent_id": null
    },
    {
        "id": 2,
        "parent_id": 1
    },
    {
        "id": 4,
        "parent_id": 2
    },
    {
        "id": 5,
        "parent_id": 4
    },
    {
        "id": 3,
        "parent_id": 1
    }
]
源码
const flatTree = (treeData = []) => {
        let flatArr = [];
        treeData?.forEach((item) => {
          const copyItem = { ...item };
          if (item.children) {
            delete copyItem.children;
          }
          flatArr.push(copyItem);
          if (item.children && item.children.length) {
            flatArr = flatArr.concat(flatTree(item.children));
          }
        });
        return flatArr;
      };

搜索树结构数据

模糊查树形结构数据

参数:

  1. searchValue: 需要模糊查询的字符串。
  2. treeArr: 原始树形结构数组。

返回: (Array): 模糊查询完成的树形结构数组。

例子:

const list = [
        {
          id: 1,
          parent_id: null,
          title: "asd",
          children: [
            {
              id: 2,
              parent_id: 1,
              title: "asdsf",

              children: [
                {
                  id: 4,
                  parent_id: 2,
                  title: "asdsg",

                  children: [
                    { id: 5, parent_id: 4, children: [], title: "asdsh" },
                  ],
                },
              ],
            },
            { id: 3, parent_id: 1, children: [], title: "asdsj" },
          ],
        },
      ];
 searchTree('asdsj',list);
 //  结果
 [
    {
        "id": 1,
        "parent_id": null,
        "title": "asd",
        "children": [
            {
                "id": 3,
                "parent_id": 1,
                "children": [],
                "title": "asdsj"
            }
        ]
    }
]
源码
const searchTree = (searchValue = "", treeArr = []) => {
        let searTreeArr = [];
        treeArr?.forEach((treeItem) => {
          if (treeItem.title.includes(searchValue)) {
            searTreeArr.push(treeItem);
          } else {
            if (treeItem.children && treeItem.children.length) {
              const chr = searchTree(searchValue, treeItem.children);
              const obj = {
                ...treeItem,
                children: chr,
              };
              if (chr && chr.length) {
                searTreeArr.push(obj);
              }
            }
          }
        });
        return searTreeArr;
      };

自定义条件搜索树结构数据

根据自定义的函数过滤树形结构数据

参数:

  1. isFilter: 自定义过滤的函数,返回值为Boolean。
  2. treeArr: 树形结构数据。

返回: (Array): 符合查询条件的树形结构数据。

例子:

const test = [
        {
          id: 1,
          name: 1,
          children: [
            {
              id: 2,
              name: 2,
              children: [
                {
                  id: 3,
                  name: 3,
                },
              ],
            },
          ],
        },
        {
          id: 4,
          name: 4,
          children: [{ id: 5, name: 5 }],
        },
      ];
const isFilter = (treeItem) => treeItem.id === 1;
filterTree(isFilter, test);
// 结果
[
        {
          id: 1,
          name: 1,
          children: [
            {
              id: 2,
              name: 2,
              children: [
                {
                  id: 3,
                  name: 3,
                },
              ],
            },
          ],
        },
]
源码
const filterTree = (isFilter, treeArr = []) => {
        let filterData = [];
        treeArr.forEach((treeItem, index) => {
          if (isFilter(treeItem, index)) {
            filterData.push(treeItem);
          } else {
            if (treeItem.children && treeItem.children.length > 0) {
              const arr = filterTree(isFilter, treeItem.children);
              const obj = {
                ...treeItem,
                children: arr,
              };
              if (arr && arr.length > 0) {
                filterData.push(obj);
              }
            }
          }
        });
        return filterData;
      };

两个数组是否相等

判断两个数组中的数据是否相等

参数:

  1. arr1: 源数组。
  2. arr2: 需要比较的数组。

返回: (Boolean): 是否相等。

例子:

isArrayEqual([1,2],[1,2]); // true
源码
const isArrayEqual = (arr1=[],arr2=[])=>{
        let isEqual = true;
        if(arr1.length !== arr2.length){
          return isEqual=false;
        }
        const arrSet = new Set(arr2);
        isEqual = arr1.every(item=> arrSet.has(item));
        return isEqual
      }

数组转number[]

将数组全部数据转为number类型

参数:

  1. arr: 需要转换的原始数据数组。

返回: (Array): 完成转换的number数组。

例子:

convertNumbersArr(['1','2']); // [1,2]
源码
const convertNumbersArr = (arr=[])=>arr.map(Number);

数组转string[]

将数组全部数据转为string类型

参数:

  1. arr: 需要转换的原始数据数组。

返回: (Array): 完成转换的string数组。

例子:

convertStringsArr([1,2]); // ['1','2']
源码
const convertStringsArr = (arr=[])=>arr.map(String);

去除数组无效值

删除数组中存在的无效值

参数:

  1. arr: 需要去除无效值的原始数据数组。

返回: (Array): 完成去除无效值的数组。

例子:

const test = ['',1,undefined,null,'2','false',0,NaN];
delInvalidValues(test);
// [1, "2", "false"]
源码
const delInvalidValues = (arr = []) => arr.filter(Boolean);

去除对象中无效值

删除对象中无效的值

参数:

  1. obj: 需要去除无效值的原始对象。

返回: (Object): 完成去除无效值的对象。

例子:

const testData = {
    a:1,
    b: '2',
    c: null,
    d: '',
    e: undefined,
    f: NaN,
    g:0
}
delInvalidValues(testData); // {a: 1, b: "2"}
源码
const delInvalidValues = (obj) => {
        const newObj = {};
        for (const [key, value] of Object.entries(obj)) {
          if (Boolean(value)) {
            newObj[key] = value;
          }
        }
        return newObj;
      };

数组元素重复次数

查看数组中元素的重复次数

参数:

  1. arr: 需要查看重复次数的数组。

返回: (Object): 记录数组元素重复次数的对象。

例子:

const test = ['qwe','qwe','dasd'];
numberOfRecords(test);
// {qwe: 2, dasd: 1}
源码
const numberOfRecords = (arr = []) => {
        const records = {};
        arr.forEach((item) => {
          if (records[item]) {
            records[item]++;
          } else {
            records[item] = 1;
          }
        });
        return records;
      };

定向查询数组重复元素次数

定向查看数组中重复元素的个数

参数:

  1. arr: 需要查看重复次数的数组。
  2. num: 需要查看的数组元素。

返回: (Number): 重复次数。

例子:

const test = ['1','asd','asd',2,3];
numberOfRecords(test,'asd'); // 2
源码
const numberOfRecords = (arr = [], num = 0) =>
        arr.reduce((times, number) => (number === num ? times + 1 : times), 0);

扁平化数组

数组的扁平化,并去除无效值

参数:

  1. arr: 需要扁平化的多维数组。

返回: (Array): 扁平化后的数组。

例子:

flatArr([1,[2],,]);// [1,2]

recursionFlatArray([1,[1,2],,]);// [1,1,2]
源码
// flat
const flatArr = (arr = [], num = Infinity) => arr.flat(num);

// 递归
const recursionFlatArray = (arr = []) =>
        []
          .concat(
            ...arr.map((item) =>
              Array.isArray(item) ? recursionFlatArray(item) : item
            )
          )
          .filter(Boolean);

指定深度扁平数组

根据指定的深度扁平化数组,并去除无效值

参数:

  1. arr: 需要扁平化的多维数组。
  2. num: 指定的深度。

返回: (Array): 扁平化后的数组。

例子:

recursionFlatArrayNumber([1,2,[23,,]]); // [1,2,23]
源码
// reduce实现
const recursionFlatArrayNumber = (arr = [], num = 1) =>
        arr
          .reduce(
            (array, current) =>
              array.concat(
                num > 1 && Array.isArray(current)
                  ? recursionFlatArrayNumber(current, num - 1)
                  : current
              ),
            []
          )
          .filter(Boolean);

查询数组中某个值的索引

查询数组中某个元素的全部索引

参数:

  1. arr: 需要查找的数组。
  2. value: 指定查找的值。

返回: (Array): 符合查找值的全部索引数组。

例子:

const test = [1,,2,1,3,1,1];
indexOfAll(test,1); // [0, 3, 5, 6]
源码
const indexOfAll = (arr = [], value) =>
        arr.reduce(
          (indexArr, item, index) =>
            value === item ? [...indexArr, index] : indexArr,
          []
        );

数组交集

查找两个数组的交集

参数:

  1. arr1: 源数组。
  2. arr2: 对比的数组。

返回: (Array): 返回两个数组公有数据的数组。

例子:

const test = [1,2];
const test2 = [2,3];
intersection(test,test2); // [2]
源码
const intersection = (arr1 = [], arr2 = []) => {
        const arrSet = new Set(arr2);
        return arr1.filter((item) => arrSet.has(item));
      };

数组差集

查找源数组不包含的数据

参数:

  1. arr1: 源数组。
  2. arr2: 对比的数组。

返回: (Array): 返回源数组中不包含数据的数组。

例子:

const test = [1,2,6];
const test2 = [2,3,4];
subtraction(test,test2); //  [1, 6]
源码
const subtraction = (arr1 = [], arr2 = []) => {
        const arrSet = new Set(arr2);
        return arr1.filter((item) => !arrSet.has(item));
      };

延迟方法执行

延迟函数的执行

参数:

  1. fn: 延迟执行的方法。
  2. [time = 1000ms]: 延迟时间。
  3. args: 参数数组。

返回: (Number): setTimeout ID。

例子:

console.log('1');
delayFn((a,s,d)=>{
  console.log(a,s,d)
}, 2000,1,2,3);
console.log('2');
// 结果
1
2
1,2,3
源码
const delayFn = (fn, time = 1000, ...args) =>
        setTimeout(fn, time, ...args);

sleep等待

参数:

  1. [time = 1000ms]: 等待时间。

返回: (Promise):

例子:

async function test(){
  console.time('timeTaken');
  await sleep()
  console.timeEnd('timeTaken');
}
test()
源码
const sleep = (time = 1000) =>
        new Promise((res) => setTimeout(() => res("Over!"), time));

执行多个Promise

依次执行Promise数组

参数:

  1. arr: 包含Promise的数组。

返回: (Promise):

例子:

const test = [sleep,sleep];
runPromisesInSeries(test); // 依次执行
源码
const runPromisesInSeries = (arr = []) =>
        arr.reduce(
          (runRro, currentPro) => runRro.then(currentPro),
          Promise.resolve()
        );

执行一次函数

函数只执行一次

参数:

  1. fn: 回调函数。

返回: (Function): 返回新的运行函数。

例子:

const fn = onceFun(() => {
        console.log("aaa");
      });
      fn(); // aaa
      fn(); //
源码
const onceFun = (fn) => {
        let isOnce = true;
        return function (...args) {
          if (isOnce) {
            isOnce = false;
            fn.apply(this, args);
          }
        };
      };

以键的路径扁平化对象

根据对象的属性扁平化对象

参数:

  1. obj: 需要扁平化的对象。
  2. [prefix = ""]: 累加的键名,不需要传参。

返回: (Object): 返回新的扁平化对象。

例子:

const test = {a:{b:{c:{d:1,f:2}}},e:2};
flattenObject(test);
// {a.b.c.d: 1, a.b.c.f: 2, e: 2}
源码
const flattenObject = (obj, prefix = "") =>
        Object.keys(obj).reduce((newObj, key) => {
          const pre = prefix.length ? prefix + "." : "";
          if (typeof obj[key] === "object") {
            Object.assign(newObj, flattenObject(obj[key], pre + key));
          } else {
            newObj[pre + key] = obj[key];
          }
          return newObj;
        }, {});

以键的路径展开对象

根据扁平化对象的属性还原对象结构

参数:

  1. obj: 需要恢复的对象。

返回: (Object): 返回新的对象。

例子:

const test = {'a.b.c':1,f:3};
unflattenObject(test); // {a:{b:{c:1}},f:3}
源码
const unflattenObject = (obj) =>
        Object.keys(obj).reduce((newObj, keyF) => {
          if (keyF.includes(".")) {
            const keys = keyF.split(".");
            Object.assign(
              newObj,
              JSON.parse(
                `
            {
              ${keys
                .map((key, index) =>
                  index !== keys.length - 1 ? `"${key}":{` : `"${key}":`
                )
                .join("")}${obj[keyF]} ${"}".repeat(keys.length)}
            `
              )
            );
          } else {
            newObj[keyF] = obj[keyF];
          }
          return newObj;
        }, {});

字符串首字母大写

字符串的首字母大写

参数:

  1. str: 需要大写的字符串。

返回: (String): 返回新的首字母大写的字符串。

例子:

capitalize('hello'); // Hello
源码
const capitalize = ([first, ...others]) =>
        first.toUpperCase() + others.join("");

字符串首字母小写

字符串的首字母小写

参数:

  1. str: 需要小写的字符串。

返回: (String): 返回新的首字母小写的字符串。

例子:

decapitalize('Hello'); // hello
源码
const decapitalize = ([first, ...others]) =>
        first.toLowerCase() + others.join("");

每个单词首字母大写

字符串的每个单词首字母大写

参数:

  1. str: 需要大写的字符串。

返回: (String): 返回新的首字母大写的字符串。

例子:

capitalizeEveryWord('hello world!'); // Hello World!
源码
const capitalizeEveryWord = (str = "") =>
        str.replace(/\b[a-z]/g, (char) => char.toUpperCase());

判断全等

判断两个任意值是否全等

参数:

  1. a: 源数据。
  2. b: 需要对比的数据。

返回: (Boolean): 返回是否相等。

例子:

equals('asd','asd'); // true
equals([1,2,3],[1,2,3]); // true
equals({a:1,b:{a:1,c:{d:1}}},{a:1,b:{a:1,c:{d:1}}}); // true
源码
const equals = (a, b) => {
        if (a === b) return true;
        if (a instanceof Date && b instanceof Date) a.getTime() === b.getTime();
        if (!a || !b || (typeof a !== "object" && typeof b !== "object"))
          return a === b;
        if (a.prototype !== b.prototype) return false;
        let keys = Object.keys(a);
        if (keys.length !== Object.keys(b).length) return false;
        return keys.every((key) => equals(a[key], b[key]));
      };

实现apply

实现apply函数

参数:

  1. [context = window]: this对象。

返回: (Object): 返回新的对象。

例子:

const test = {name:'asd'};
function testFu(){
    console.log(this.name)
}
testFu.myApply(test); // 'asd'
源码
Function.prototype.myApply = function myApply(context = window) {
      context.fn = this;
      let result;
      if (arguments[1]) {
        if (!Array.isArray(arguments[1])) {
          result = context.fn(arguments[1]);
        } else {
          result = context.fn(...arguments[1]);
        }
      } else {
        result = context.fn();
      }
      delete context.fn; // 释放内存
      return result;
    }

实现call

实现call函数

参数:

  1. [context = window]: this对象。

返回: (Object): 返回新的对象。

例子:

const test = {name:'asd'};
function testFu(){
    console.log(this.name)
}
testFu.myCall(test); // 'asd'
源码
Function.prototype.myCall = function myCall(context = window) {
      const args = [...arguments].slice(1);
      context.fn = this;
      const result = context.fn(...args);
      delete context.fn; // 释放内存
      return result
    }

实现bind

实现bind函数

参数:

  1. [context = window]: this对象。

返回: (Function): 返回新的函数。

例子:

const test = {name:'asd'};
function testFu(){
    console.log(this.name)
}
testFu.myBind(test)(); // 'asd'
源码
Function.prototype.myBind = function (context = window) {
      const args = [...arguments].slice(1);
      const fn = this;
      const resFn = function () {
        return fn.myApply(this instanceof resFn ? this : context, args.concat(...arguments));
      }

      function tmp() {}
      tmp.prototype = this.prototype;
      resFn.prototype = new tmp();
      return resFn
    }

实现New

实现New关键字

参数: 1.fn: 构造函数。 2. args: 参数数组。

返回: (Object): 返回新的对象。

例子:

function test(){
    this.name = 'asd';
}
myNew(test); // {name: 'asd'}
源码
function myNew(fn, ...args) {
      // 1. 创建一个新的对象
      // 2. 将新对象的的原型指向fn的原型
      // 3. 改变fn的上下文this,将剩余参数传递
      // 4. 根据fn的返回值判断具体返回什么

      // 1,2合并
      const obj = Object.create(fn.prototype);
      const result = fn.apply(obj, args);
      return result instanceof Object ? result : obj;
    }

解析URL参数

根据输入的URL解析包含在URL中的参数

参数:

  1. url: 想要解析参数的完整URL字符串。

返回:

(Boolean | Object): 错误返回false,正确返回包含参数的对象。

例子:

const test = `https://****com/searchPage?wd=URLSearchParams&age=18`;
getSearchParams(test); // {wd: "URLSearchParams", age: "18"}
源码
// 普通实现
const getSearchParams = (url = "") => {
        const index_ = url.indexOf("?");
        if (!~index_) {
          return false;
        }
        const searchParamsArr = url.slice(index_ + 1).split("&");
        const paramsObj = {};
        for (const paramsStr of searchParamsArr) {
          const [key, value] = paramsStr.split("=");
          paramsObj[key] = decodeURIComponent(value);
        }
        return paramsObj;
      };
// URLSearchParams 实现
const getSearchParams = () => {
        const searchPar = new URLSearchParams(window.location.search);
        const paramsObj = {};
        for (const [key, value] of searchPar.entries()) {
          paramsObj[key] = value;
        }
        return { paramsObj, searchPar };
      };
const getSearchParams = (URL) => JSON.parse('{"' + decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g,
    '","').replace(/=/g,
    '":"') + '"}');

转义字符串中的特别字符

参数:

  1. str: 想要转义的字符串。
  2. specialCharacters: 想要转义字符数组。
  3. strArr: 被转义的字符串数组。

返回:

(Array): 返回包含转义字符的数组。

(String): 返回反转义的字符串。

例子:

// 转义
const testString = handleOfCompiledCharacters('hello&='); 
// ["h", "e", "l", "l", "o", "customize,38", "customize,61"]
// 反转义
handleDecompiledCharacters(testString); // 'hello&='
源码
// 转义字符串函数
function handleOfCompiledCharacters(str, specialCharacters = ['&', '=']) {
  const strArr = [...str];
  const newStrArr = strArr.map((text, index) => {
    if (specialCharacters.includes(text)) {
      return `customize,${str.charCodeAt(index)}`;
    }
    return text;
  });
  return newStrArr;
}

// 反转义字符串函数
function handleDecompiledCharacters(strArr) {
  const newStrArr = strArr.map((text) => {
    if (text.includes('customize')) {
      const [, str] = text.split(',');
      return String.fromCharCode(+str);
    }
    return text;
  });
  return newStrArr.join('');
}

数组乱序

随机打乱数组中数据的位置。

参数:

  1. arr: 想要打乱位置的数组。

返回:

(Array): 返回乱序数组。

例子:

const arr = [1,2,3,4,5]
arrayOutOfOrder(arr); // [3,2,4,5,1]
源码
const arrayOutOfOrder = (arr = []) => arr.sort(() => 0.5 - Math.random());

复制文字到剪贴板

参数:

text: 想要复制的字符串。

返回:

(Promise): 返回一个Promise,可以判断成功或者失败。

例子:

copyToClipboard("Hello World");
源码
const copyToClipboard = (text) => navigator.clipboard.writeText(text);

获取在网页上鼠标选中的文本

参数: 无

返回:

(String): 鼠标选中的文本。

例子:

// 先使用鼠标在网页上选中文字,在调用函数
getSelectedText();
源码
const getSelectedText = () => window.getSelection().toString();

从对象数组中提取属性的值

参数:
arr: 对象数组。
property:想要获取的属性。

返回:

(Array): 返回一个属性值的数组。

例子:

  const example = [{      name: '张飞',      age: 20    },    {      name: '李逵',      age: 25    },    {      name: '马超',      age: 30    },  ]
  pluck(example, 'name'); // ['张飞', '李逵', '马超']
源码
const pluck = (arr, property) => arr.map((obj) => obj[property]);

对象转URL

参数:

baseURL: 基础的URL。
obj: 转换的对象。

返回:
(string):拼接好的完整URL。

例子:

const baseURL = 'https://www.google.com/search';
const obj = {q:'你好!'}

ObjToURL(baseURL,obj); // 'https://www.google.com/search?&q=%E4%BD%A0%E5%A5%BD%EF%BC%81'
源码
const ObjToURL = (baseUrl, obj) =>
  `${baseUrl}${Object.keys(obj).reduce(
    (acc, key) => `${acc}&${key}=${encodeURIComponent(obj[key])}`,
    `?`
  )}`;

Promise 请求超时

参数:
promise:接口,或者是 new Promise()。 ms: 超时时间。

返回:
(Promise | 报错):未超时返回正确的Promise,否则 报错!

例子:

// 报错
timeout(
  new Promise((resolve, reject) => setTimeout(resolve, 1000, "test")),
  200
);  
// 成功
timeout(
  new Promise((resolve, reject) => setTimeout(resolve, 1000, "test")),
  2000
);
源码
// 请求超时 实现方式 1
function timeout(promise, ms) {
  return new Promise((resolve, reject) => {
    promise.then(resolve, reject);
    setTimeout(() => reject(new Error("timeout")), ms);
  });
}
// 请求超时 实现方式 2
function timeout(promise, ms) {
  return Promise.race([
    promise,
    new Promise((res, rej) => {
      setTimeout(() => res(new Error("timeout")), ms);
    }),
  ]);
}

获取前几个完成的 Promise

参数:
promises: Array<promises>, 包含 promises 的数组。 number: 获取前几个成功的 Promise , 数字。

返回:
(Array<promises>): 返回前几个成功的 Promise。

例子:

const arr = [
  new Promise((res) => {
    setTimeout(() => {
      res(1);
    }, 1000);
  }),
  new Promise((res) => {
    setTimeout(() => {
      res(2);
    }, 1010);
  }),
  new Promise((res) => {
    setTimeout(() => {
      res(3);
    }, 1100);
  }),
  new Promise((res) => {
    setTimeout(() => {
      res(4);
    }, 1200);
  }),
  new Promise((res) => {
    setTimeout(() => {
      res(5);
    }, 1300);
  }),
];
PromiseAll(arr,3).then(res=>{
console.log(res);// [1,2,3]
})
源码
function PromiseAll(promises,number=1) {
  return new Promise((resolve, reject) => {
    let count = 0;
    let result = [];
    promises.forEach((item, index) => {
      item.then((res) => {
        count++;
        result[index] = res;
        if (count === number) {
          resolve(result);
        }
      });
    });
  });
}

后期不定时更新......