前端项目常用函数

前端项目常用函数

抄自某大佬之手,借鉴学习一下
主要有一些前端项目常用到的重要函数,例如 防抖, 节流, 数组扁平化,数组扁平化,深度拷贝,深度拷贝



前言

后面的代码采用Typescrip进行编写
直接上代码吧以及一些应用用的场景


一、代码部分

1.防抖

应用场景 比如页面上有一个输入框避免,平凡输入导致屏幕内容频繁更新
作用 在指定的时间内只运行最后一次

代码如下(示例):

// 函数防抖 (只执行最后一次点击)
const debounce = (fn: Function, delay = 300) => {
  let timer: NodeJS.Timeout | null;
  return function(...args: any) {
      timer && clearTimeout(timer);
      timer = setTimeout(() => {
          timer = null;
          // @ts-ignore
          fn.apply(this, args);
      }, delay);
  };
};

2.节流

应用场景 应用场景其实与节流的类似,需要频繁地进行一个操作,让函数在一定的时间内只执行一次
作用 在指定的时间内只运行一次对应的函数

// 节流(n秒内只下执行一次)
const throttle = (fn: any, delay = 500) => {
  let flag = false;
  return function(...args: any) {
      if (!flag) {
          flag = true;
          setTimeout(() => {
              console.log(flag);

              flag = false;
              // @ts-ignore
              fn.apply(this, args);
          }, delay);
      }
  };
};

3.数组扁平化

应用场景 要将一个多维的数组降为一维数组
作用 将多维数组快速降维一维

// 数组扁平化
const flatten = (arr, depth = 1) => arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []);

4.函数柯里化

应用场景 需要分装一个函数(通过这个函数重新返回函数)
作用 对原始函数进行柯里化的封装

// 柯里化
const curry = (fn: Function) => {
  if (typeof fn !== "function") {
    throw new Error("No function provided");
  }
  return function curriedFn(...args: any[]) {
    if (args.length < fn.length) {
      return (...argus: any[]) => curriedFn(...args, ...argus);
    }
    return fn(...args);
  }
}

5.深度拷贝

应用场景 需要深度拷贝得到对象而不是原始数据的引用
作用 深度拷贝原始数据,让后续的操作更加安全

// 深度拷贝
const deepClone = (source:any) => {
  if (!source || typeof source !== 'object') {
    return source;
  }
  var targetObj: any[] | { [index:string]: any} = source.construct === Array ? [] : {};
  for (var key in source) { 
    if (source.hasOwnProperty(key)) {
      if (source[key] && typeof source[key] === 'object') {
        targetObj[key] = source[key].construct === Array ? [] : {};
        targetObj[key] = deepClone(source[key]);
      } else {
        targetObj[key] = source[key];
      }
    }
  }
  return targetObj;
}

6.判断函数是否为Promise函数

作用 判断函数是否为Promise函数

//是否为Promise函数
// @ts-ignore
export const isPromise = (str:any) => Object.prototype.toString.call(str) === '[object Promise]'

7.使用setTimeout实现函数的定时执行

作用定时执行函数
使用场景可以借助这个实现轮询

/**
 * 用于实现轮询
 * @param {轮询的操作} fn 
 * @returns 关闭轮询的handler
 */
const PollMessage = (fn) => {
  fn();
  let time = 5000;
  let key = true;
  const ticker = () => {
    if (!key) {
      time = 10000;
    } else {
      time = 5000;
    }
    setTimeout(() => {
      if (key) {
        fn()
      }
      ticker()
    }, time);
  };
  ticker();
  return (newKey) => {
    key = newKey;
  }
}

8. 一段时间内限定执行

使用场景比如一些输入框做避免平凡操作的,例如一分钟之内只能发送n条信息

/**
 * 避免过于频繁的操作
 * @param {要执行的函数} fn 
 */
const reduceRun = (fn) => {
  let historyContent = [];
  return () => {
    let taskTime = moment().valueOf();
    historyContent = historyContent.filter( itemTask => taskTime - itemTask < 60000 )
    if (historyContent.length >= 3) {
      notification.warning({message:"操作过于频繁,请稍后再试"})
    } else {
      fn()
    }
    historyContent.push(taskTime)
  }
}

9. 获取url中的参数

使用场景:前端需要获取请求的param参数时:

/**
 * 获取url中的参数
 * @returns 
 */
const getParams = () => {
  const search = location.search;
  console.dir(location)
  var reg = /(\w+)=([^&]+)/g,
    params = {},
    result = null;
  
  while ((result = reg.exec(search))) {
    params[result[1]] = decodeURI(result[2]);
  }
  return params;
}

10.其他

作用 对原始字符串的处理


// 去除前后空格
export const empty = (str: string) => str.replace(/^\s+|\s+$/g, '');

// 去除所有空格
export const emptyAll = (str: string) => str.replace(/\s/g, '');

// 是否包含英文
export const includeEn = (str: string) => str.search(/[a-zA-Z]+/) > -1;

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值