#说明

此处是杂项工具包,就各种零碎的工具函数整合

笔记分享:hongjilin

一、工具包1—2020

该模块封装于2020疫情本人撰写 nodejs+vue搭建校园疫情防控系统实战项目(全栈项目)项目期间,

当时编程习惯以及编程基础还不是很好,可以自行更正,如赋值解构等知识可以运用其中等

```javascript /杂项工具类/

/**

  • yyyyMMddhhmmss格式常量
  • @type {string} */ const f14 = “yyyyMMddhhmmss”;

/**

  • yyyy-MM-dd hh:mm:ss格式常量
  • @type {string} */ const f19 = “yyyy-MM-dd hh:mm:ss”;

/**

  • 创建一个id
  • 以当前的时间yyyyMMddhhmmss+5位随机数组成一个19位的id
  • @return {string} / let newId = function () { let c = new Date().format(f14); let r = Math.round(Math.random()(100000)); return c + r; }

/**

  • 获取当前时间yyyyMMddhhmmss的字符串
  • @return {void | string | } / let getDate14 = function () { return new Date().format(f14); }

/**

  • 获取当前时间yyyy-MM-dd hh:mm:ss的字符串
  • @return {void | string | } / let getDate19 = function () { return new Date().format(f19); }

/**

  • 获取昨天的日期
  • @return {void | string | } / let getYestoday = ()=>{ let day1 = new Date(); day1.setDate(day1.getDate() - 1); return day1.format(“yyyy-MM-dd”); }

/**

  • 获取当前时间yyyy-MM-dd hh:mm:ss的字符串
  • @return {void | string | } / let getDate10 = function () { return new Date().format(‘yyyy-MM-dd’); }

/**

  • 验证字符串长度是否在最大的长度范围内
  • @param str
  • @param maxLength
  • @return {boolean} */ let validLength = function (str, maxLength) { // 判断字符串是否存在 if (!str) {

    1. return false;

    }

    // 判断是否是字符串 if (typeof str != ‘string’) {

    1. return false;

    }

    // 判断字符串长度 if (str.length <= maxLength) {

    1. return true;

    } else {

    1. return false;

    } }

/**

  • 批量验证长度 *
  • @param arr [{str:str,maxlength:length}] */ let validLengthBatch = function (arr) { for (let i = 0, l = arr.length; i < l; i ++) {
    1. let item = arr[i];
    2. if (!validLength(item.str, item.maxLength)) {
    3. console.log(item.str);
    4. console.log(item.maxLength);
    5. return false;
    6. }
    } return true; }

/**

  • 格式化分页页码格式 当pageNo不存在的时候就返回1;
  • @param pageNo
  • @returns {} / let formatPageNo = function (pageNo) { if (pageNo && parseInt(pageNo) > 0) {
    1. return parseInt(pageNo);
    } return 1; }

/**

  • 格式化分页每页条数 当pageSize不存在的时候就返回10
  • @param pageSize */ let formatPageSize = function (pageSize) { if (pageSize && parseInt(pageSize) > 0) {
    1. return parseInt(pageSize);
    } return 10; } //判断是否为图片格式函数 let IsPicture =function(){ let strFilter=”.jpeg|.gif|.jpg|.png|.svg|.pic|.bmp|” if (this.indexOf(‘.’)>-1){
    1. let p=this.lastIndexOf(".")
    2. let strPostfix=this.substring(p,this.length)+"|"
    3. strPostfix=strPostfix.toLowerCase()
    4. if (strPostfix.indexOf(strPostfix)>-1) return true
    } return false; } //时间格式 Date.prototype.format = function(fmt) { var o = {
    1. "M+" : this.getMonth()+1, //月份
    2. "d+" : this.getDate(), //日
    3. "h+" : this.getHours(), //小时
    4. "m+" : this.getMinutes(), //分
    5. "s+" : this.getSeconds(), //秒
    6. "q+" : Math.floor((this.getMonth()+3)/3), //季度
    7. "S" : this.getMilliseconds() //毫秒
    }; if(/(y+)/.test(fmt)) {
    1. fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    } for(var k in o) {
    1. if(new RegExp("("+ k +")").test(fmt)){
    2. fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
    3. }
    } return fmt; } /*
  • @param req
  • @param resp / let error=(resp,msg)=>{ resp.status(500); resp.send(msg); } /验证密码格式函数 必须为字母加数字且长度不小于8位 */ let CheckPassWord=(password) =>{ let str = password; if (str == null || str.length <8) {
    1. return false;
    } let reg1 = new RegExp(/^[0-9A-Za-z]+$/); if (!reg1.test(str)) {
    1. return false;
    } let reg = new RegExp(/[A-Za-z].[0-9]|[0-9].[A-Za-z]/); if (reg.test(str)) {
    1. return true;
    } else {
    1. return false;
    } }

module.exports = { newId, getDate14, getDate19, getDate10, validLength, validLengthBatch, formatPageNo, formatPageSize, getYestoday, error, IsPicture, CheckPassWord }

  1. <a name="247b3ca2"></a>
  2. # 二、工具包2-`2021`
  3. > 该部分记录于2021年4月,原因是经过半年学习,编程能力有所提升,所需技术不同,所阅读的代码量增加,当然,也有看到好的工具函数摘录<br />
  4. 加上之前的某些杂项工具函数都是`js`,如今多用的`typeScript`,有了不一样的需求与写法
  5. <a name="33a22d82"></a>
  6. ## Ⅰ-代码
  7. > ```typescript
  8. class Tool {
  9. isUndefined = (data: any) => {
  10. return data === undefined;
  11. };
  12. isDefined = (data: any) => {
  13. return !this.isUndefined(data);
  14. };
  15. // 传入一个可执行字符串,并且运行
  16. evalString = (string: string, needReturn?: boolean) => {
  17. let newString = string;
  18. if (needReturn) {
  19. newString = `return ${string}`;
  20. }
  21. let evalFunction = new Function(newString);
  22. return evalFunction();
  23. };
  24. /**
  25. * 四舍五入保留n位小数
  26. */
  27. roundNumber = (num: number, digits?: number): number => {
  28. if (!digits) {
  29. return Math.round(num);
  30. } else {
  31. let digitsPow = Math.pow(10, digits);
  32. return Math.round(num * digitsPow) / digitsPow;
  33. }
  34. };
  35. downloadFile = (url: string, filename?: string) => {
  36. const a = document.createElement('a');
  37. a.href = url;
  38. if (filename) a.download = filename;
  39. document.body.appendChild(a);
  40. a.click();
  41. };
  42. isProductionEnv = () => {
  43. return process.env.API_ENV === 'prod';
  44. };
  45. //选中文本
  46. textSelect = (element) => {
  47. const start = 0;
  48. const end = element.value.length;
  49. if (element.createTextRange) {
  50. //IE浏览器
  51. var range = element.createTextRange();
  52. range.moveStart('character', -end);
  53. range.moveEnd('character', -end);
  54. range.moveStart('character', start);
  55. range.moveEnd('character', end);
  56. range.select();
  57. } else {
  58. element.setSelectionRange(start, end);
  59. element.focus();
  60. }
  61. };
  62. //公用排序方法
  63. setSorter = (field: string, order: string): Object => {
  64. let sorter: Object;
  65. if (order) {
  66. sorter = {
  67. field: field,
  68. order: order.replace('end', ''),
  69. };
  70. }
  71. return sorter;
  72. };
  73. // 节流
  74. throttle = (fn: Function, interval: number) => {
  75. let canRun = true;
  76. return () => {
  77. if (!canRun) {
  78. return;
  79. }
  80. canRun = false;
  81. setTimeout(() => {
  82. fn();
  83. canRun = true;
  84. }, interval);
  85. };
  86. };
  87. // 防抖
  88. deBounce = (
  89. fn: (...args: any[]) => any,
  90. interval: number
  91. ): ((...args: any[]) => any) => {
  92. let timer = null;
  93. return (e) => {
  94. if (timer) {
  95. clearTimeout(timer);
  96. timer = null;
  97. }
  98. timer = setTimeout(() => {
  99. fn(e);
  100. }, interval);
  101. };
  102. };
  103. /**
  104. * 防抖1
  105. * @param fnc 传入函数
  106. * @param params
  107. * @param t
  108. * @returns
  109. 调用示例:onClick={tool.DebounceSendSMSCode(sendSMSCode, [phoneItem, index], 300)}
  110. */
  111. DebounceSendSMSCode = (fnc,params, t) => {
  112. let delay = t || 200; // 默认0.2s
  113. let timer;
  114. return function () {
  115. if (timer) {
  116. clearTimeout(timer);
  117. }
  118. timer = setTimeout(() => {
  119. timer = null;
  120. fnc(...params)
  121. }, delay);
  122. }
  123. }
  124. // 深拷贝
  125. deepClone = (obj) => {
  126. const isObject = (args) =>
  127. (typeof args === 'object' || typeof args === 'function') &&
  128. typeof args !== null;
  129. if (!isObject) throw new Error('Not Reference Types');
  130. let newObj = Array.isArray(obj) ? [...obj] : { ...obj };
  131. Reflect.ownKeys(newObj).map((key) => {
  132. newObj[key] = isObject(obj[key]) ? this.deepClone(obj[key]) : obj[key];
  133. });
  134. return newObj;
  135. };
  136. }
  137. export const tool = new Tool();
  138. export default Tool;