an-function
Version:
js中常用的util方法;比如处理日期的函数,a连接下载,解析url,防抖,节流,基于webWork的定时器,websocket连接等等
1 lines • 12.7 kB
JavaScript
"use strict";function _toPropertyKey(e){var t=function(e){if("object"!=_typeof(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=_typeof(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==_typeof(t)?t:t+""}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n<t;n++)o[n]=e[n];return o}function _typeof(e){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof(e)}function _deepCloneRecursive(e,t,n){if(t.has(e))return t.get(e);if(null===e||"object"!==_typeof(e))return e;if(e instanceof Date)return new Date(e);if(e instanceof RegExp)return new RegExp(e);var o=Array.isArray(e)?[]:{};for(var r in t.set(e,o),e)(n||Object.prototype.hasOwnProperty.call(e,r))&&(o[r]=_deepCloneRecursive(e[r],t,n));return o}function aDownLoad(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=window.document.createElement("a");n.style.display="none",n.setAttribute("download",t),n.setAttribute("href",e),document.body.appendChild(n),n.click(),document.body.removeChild(n)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.aDownLoad=aDownLoad,exports.aDownLoad2=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=new Blob([e]),o=URL.createObjectURL(n);aDownLoad(o,t),setTimeout(function(){return URL.revokeObjectURL(o)},100)},exports.anWebSocket=exports.anTimeout=exports.anInterval=void 0,exports.chinaDate=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"-";null==e&&(e=new Date),"string"==typeof e&&(e=e.replace(/-/g,"/")),null==t&&(t="/");var n=new Date(e);if(isNaN(n.getTime()))throw new RangeError('chinaDate: 无效的日期入参 "'.concat(e,'"'));var o=n.getFullYear(),r=("00"+(n.getMonth()+1)).slice(-2),i=("00"+n.getDate()).slice(-2),s=("00"+n.getHours()).slice(-2),a=("00"+n.getMinutes()).slice(-2),c=("00"+n.getSeconds()).slice(-2),u=new Date(o+"/"+r+"/"+i+" 00:00:00").getTime(),l=new Date(o+"/"+r+"/"+i+" 23:59:59").getTime();return{fengefu:t,newDate:n,nian:o,yue:r,ri:i,shi:s,fen:a,miao:c,date:o+t+r+t+i+" "+s+":"+a+":"+c,date0:o+t+r+t+i+" 00:00:00",date59:o+t+r+t+i+" 23:59:59",nyr:o+t+r+t+i,sfm:s+":"+a+":"+c,number:n.getTime(),get0:u,get59:l}},exports.deepClone=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:new WeakMap,n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if("function"==typeof structuredClone)try{return structuredClone(e)}catch(e){}return _deepCloneRecursive(e,t,n)},exports.fileToBase64=function(e){return new Promise(function(t,n){try{var o=new FileReader;o.onload=function(){t(o.result)},o.onerror=function(){n(o.error)},o.readAsDataURL(e)}catch(e){n(e)}})},exports.getLengthArray=function(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=[],n=1;n<=e;n++)t.push(n);return t},exports.getUrlParams=function(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:window.location.search,n=new URLSearchParams(t),o={},r=function(e){var t="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!t){if(Array.isArray(e)||(t=function(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(e,t):void 0}}(e))){t&&(e=t);var n=0,o=function(){};return{s:o,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r,i=!0,s=!1;return{s:function(){t=t.call(e)},n:function(){var e=t.next();return i=e.done,e},e:function(e){s=!0,r=e},f:function(){try{i||null==t.return||t.return()}finally{if(s)throw r}}}}(new Set(n.keys()));try{for(r.s();!(e=r.n()).done;){var i=e.value,s=n.getAll(i);o[i]=s.length>1?s:s[0]}}catch(e){r.e(e)}finally{r.f()}return o},exports.objKeysHasValue=void 0,exports.objKeysHasValue=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return"some"===(arguments.length>2&&void 0!==arguments[2]?arguments[2]:"some")?t.some(function(t){return![null,"",void 0].includes(e[t])}):t.every(function(t){return![null,"",void 0].includes(e[t])})};var worker,listeners,idCounter,anInterval=exports.anInterval=(listeners=new Map,idCounter=0,{on:function(e,t){var n,o;worker||(n=new Blob(["\n const intervals = new Map();\n onmessage = function(event) {\n const { command, id, time } = event.data;\n \n if (command === 'clear') {\n clearTimeout(intervals.get(id));\n intervals.delete(id);\n return;\n }\n\n if (intervals.has(id)) {\n clearTimeout(intervals.get(id));\n }\n \n function anIntervalF() {\n postMessage({ id });\n intervals.set(id, setTimeout(anIntervalF, time));\n }\n // 使用 setTimeout 延迟第一次执行\n intervals.set(id, setTimeout(anIntervalF, time));\n }\n "],{type:"text/javascript"}),o=URL.createObjectURL(n),worker=new Worker(o),URL.revokeObjectURL(o),worker.onerror=function(e){},worker.addEventListener("message",function(e){var t=e.data.id;listeners.has(t)&&listeners.get(t).forEach(function(e){return e()})}));var r="timer_"+idCounter++;return listeners.has(r)||listeners.set(r,[]),listeners.get(r).push(e),worker.postMessage({id:r,time:t}),r},off:function(e){var t;listeners.has(e)&&(listeners.delete(e),null===(t=worker)||void 0===t||t.postMessage({command:"clear",id:e}))}}),anTimeout=exports.anTimeout=function(){var e,t=new Map,n=0;return{on:function(o,r){var i,s;e||(i=new Blob(["\n const intervals = new Map();\n onmessage = function(event) {\n const { command, id, time } = event.data;\n \n if (command === 'clear') {\n clearTimeout(intervals.get(id));\n intervals.delete(id);\n return;\n }\n\n if (intervals.has(id)) {\n clearTimeout(intervals.get(id));\n }\n \n function anIntervalF() {\n postMessage({ id });\n }\n // 使用 setTimeout 延迟第一次执行\n intervals.set(id, setTimeout(anIntervalF, time));\n }\n "],{type:"text/javascript"}),s=URL.createObjectURL(i),e=new Worker(s),URL.revokeObjectURL(s),e.onerror=function(e){},e.addEventListener("message",function(e){var n=e.data.id;t.has(n)&&(t.get(n).forEach(function(e){return e()}),t.delete(n))}));var a="timer_"+n++;return t.has(a)||t.set(a,[]),t.get(a).push(o),e.postMessage({id:a,time:r}),a},off:function(n){var o;t.has(n)&&(t.delete(n),null===(o=e)||void 0===o||o.postMessage({command:"clear",id:n}))}}}();exports.anWebSocket=function(){return e=function anWebSocket(e){var t=this,n=e.url,o=e.sendMessage,r=e.webSocketBack,i=e.pingTimeout,s=void 0===i?5e3:i,a=e.pongTimeout,c=void 0===a?4e3:a,u=e.reconnectTimeout,l=void 0===u?4e3:u,f=e.pingMsg,d=void 0===f?"heartbeat":f,h=e.repeatLimit,v=void 0===h?3:h,p=e.showLog,m=void 0!==p&&p;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,anWebSocket),this.log=function(){},this.error=function(){},this.warn=function(){},!0===m&&(this.log=function(){var e;(e=console).log.apply(e,arguments)},this.error=function(){var e;(e=console).error.apply(e,arguments)},this.warn=function(){var e;(e=console).warn.apply(e,arguments)}),!n)throw new Error("WebSocket URL is required");this.opts={url:n,sendMessage:o,webSocketBack:r,pingTimeout:s,pongTimeout:c,reconnectTimeout:l,pingMsg:d,repeatLimit:v},this.ws=null,this.repeat=0,this.lockReconnect=!1,this.forbidReconnect=!1,this.pingTimeoutId=null,this.pongTimeoutId=null,this.reconnectTimeoutId=null,this.activeConnections=0,this.onclose=function(){return t.log("Connection closed")},this.onerror=function(e){return t.error("Error:",e)},this.onopen=function(){return t.handleOpen()},this.onmessage=function(e){return t.handleMessage(e)},this.onreconnect=function(){return t.log("Reconnecting (".concat(t.repeat).concat(t.opts.repeatLimit?"/"+t.opts.repeatLimit:"",")"))},this.createWebSocket()},t=[{key:"createWebSocket",value:function(){try{this.forbidReconnect||this.ws&&this.ws.readyState!==WebSocket.CLOSED||(this.ws&&(this.close(!1),this.ws=null),this.ws=new WebSocket(this.opts.url),this.initEventHandle(),this.activeConnections++)}catch(e){this.error("创建ws连接失败:",e),this.forbidReconnect||(this.log("创建ws连接失败,即将断线重连"),this.reconnect())}}},{key:"initEventHandle",value:function(){var e=this;this.ws.onclose=function(t){e.onclose(t),e.forbidReconnect||(e.log("关闭了,即将断线重连"),e.reconnect()),e.activeConnections=Math.max(0,e.activeConnections-1)},this.ws.onerror=function(t){e.onerror(t),e.forbidReconnect||(e.log("onerror,即将断线重连"),e.reconnect()),e.activeConnections=Math.max(0,e.activeConnections-1)},this.ws.onopen=function(){e.repeat=0,e.onopen(),e.heartCheck()},this.ws.onmessage=function(t){e.onmessage(t),e.heartCheck()}}},{key:"send",value:function(e){try{if(!this.isConnected())return this.warn("连接失败"),!1;var t;try{t="string"==typeof e?e:JSON.stringify(e)}catch(e){return this.error("消息序列化失败:",e),!1}return this.ws.send(t),!0}catch(e){return this.error("发送失败:",e),this.forbidReconnect||this.reconnect(),!1}}},{key:"heartStart",value:function(){var e=this;this.forbidReconnect||(this.log("".concat(this.opts.pingTimeout,"毫秒后发送心跳")),this.pingTimeoutId=anInterval.on(function(){e.log("当前连接状态是否正常",e.isConnected()),e.isConnected()&&(e.log("客户端-发送心跳"),e.ws.send(e.opts.pingMsg),e.pongTimeoutId&&anTimeout.off(e.pongTimeoutId),e.pongTimeoutId=anTimeout.on(function(){e.error("心跳超时,关闭连接(心跳发出后直到现在都未收到服务器的回复)"),e.ws.close(1e3,"pong timeout")},e.opts.pongTimeout))},this.opts.pingTimeout))}},{key:"close",value:function(){if(arguments.length>0&&void 0!==arguments[0]&&arguments[0]&&(this.forbidReconnect=!0),this.heartReset(),this.ws){var e=this.ws;e.onclose=null,e.onerror=null,e.onopen=null,e.onmessage=null,[WebSocket.OPEN,WebSocket.CONNECTING].includes(e.readyState)&&e.close(1e3,"Normal closure"),this.ws=null,this.activeConnections=Math.max(0,this.activeConnections-1)}}},{key:"reconnect",value:function(){var e=this;if(this.forbidReconnect||this.shouldStopReconnect()||this.lockReconnect)return this.log("停止重连"),void this.heartReset();this.lockReconnect=!0,this.reconnectTimeoutId=anTimeout.on(function(){e.reconnectTimeoutId=null,e.lockReconnect=!1,e.forbidReconnect||(e.log("重新连接..."),e.repeat++,e.createWebSocket())},this.opts.reconnectTimeout)}},{key:"heartReset",value:function(){anInterval.off(this.pingTimeoutId),anTimeout.off(this.pongTimeoutId),this.reconnectTimeoutId&&(anTimeout.off(this.reconnectTimeoutId),this.reconnectTimeoutId=null),this.pingTimeoutId=null,this.pongTimeoutId=null}},{key:"heartCheck",value:function(){this.log("心跳检测"),this.heartReset(),this.heartStart()}},{key:"destroy",value:function(){this.close(!0)}},{key:"shouldStopReconnect",value:function(){return this.opts.repeatLimit>0&&this.repeat>=this.opts.repeatLimit}},{key:"handleOpen",value:function(){this.log("连接成功"),this.opts.sendMessage&&this.isConnected()&&this.ws.send("string"==typeof this.opts.sendMessage?this.opts.sendMessage:JSON.stringify(this.opts.sendMessage))}},{key:"handleMessage",value:function(e){"function"==typeof this.opts.webSocketBack&&this.opts.webSocketBack(e)}},{key:"setEventHandlers",value:function(e){var t=this;["onopen","onclose","onerror","onmessage","onreconnect"].forEach(function(n){e[n]&&(t[n]=e[n])})}},{key:"getState",value:function(){var e,t;return null!==(e=null===(t=this.ws)||void 0===t?void 0:t.readyState)&&void 0!==e?e:WebSocket.CLOSED}},{key:"isConnected",value:function(){var e;return(null===(e=this.ws)||void 0===e?void 0:e.readyState)===WebSocket.OPEN}},{key:"getActiveConnections",value:function(){return this.activeConnections}}],t&&function(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();