@ryanuo/utils
Version:
提供多种实用工具函数,涵盖算法、浏览器操作、网络请求等多个领域
2 lines (1 loc) • 10.9 kB
JavaScript
import M from"dayjs";import x from"query-string";import{Decimal as c}from"decimal.js";const d=e=>Object.prototype.toString.call(e);function I(e){return d(e).slice(8,-1).toLowerCase()}function $(e,t=4){return e===0||Number.isNaN(e)?0:Number(e.toFixed(t))}function g(e){if(e===null||typeof e!="object")return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp)return new RegExp(e.source,e.flags);if(Array.isArray(e))return e.map(n=>g(n));const t={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=g(e[n]));return t}function R(e){return typeof e=="boolean"}function B(e){return typeof e=="number"&&!Number.isNaN(e)}const v=e=>typeof e=="function",O=e=>typeof e=="string",E=e=>d(e)==="[object Object]",S=e=>E(e)&&Object.keys(e).length===0,q=e=>d(e)==="[object Undefined]",k=e=>d(e)==="[object Null]",L=e=>d(e)==="[object RegExp]",N=e=>d(e)==="[object Date]";function U(){return typeof window<"u"&&typeof document<"u"}function A(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function Y(e){return function t(...n){return n.length>=e.length?e(...n):function(...r){const o=[...n,...r];return t(...o)}}}function D(e){try{return JSON.parse(e)}catch{return null}}function H(e,t,n=!1){let r=null;return(...o)=>{r!==null&&window.clearTimeout(r),n&&r===null&&e(...o),r=window.setTimeout(()=>{n||e(...o),r=null},t)}}function z(e,t,n=!0){let r=0,o=null;return(...i)=>{const u=Date.now(),a=u-r,s=()=>{e(...i),r=u};n&&a>=t?s():o===null&&(o=window.setTimeout(()=>{(!n||a<t)&&s(),o=null},n?t-a:t))}}function J(e,t="YYYY-MM-dd"){if(!N(e))throw new TypeError("Parameter must be a valid Date.");const n=e.getFullYear().toString(),r={Y:4,y:2,M:2,d:2,H:2,h:2,m:2,s:2,S:3,q:1},o={"Y+":()=>n,"y+":u=>n.slice(-u.length),"M+":(e.getMonth()+1).toString(),"d+":e.getDate().toString(),"H+":e.getHours().toString(),"h+":()=>(e.getHours()%12||12).toString(),"m+":e.getMinutes().toString(),"s+":e.getSeconds().toString(),"q+":Math.floor((e.getMonth()+3)/3).toString(),"S+":e.getMilliseconds().toString()};let i;for(const u in o)i=t.match(new RegExp(u,"g")),i?.forEach(a=>{const s=u.charAt(0),w=r[s]||a.length,l=o[u],f=v(o[u])?l(a):l;t=t.replace(a,f.toString().padStart(Math.max(a.length,w),"0"))});return t}const _=M;function G(e,t,n){n.forEach(r=>e.classList[t](r))}function W(e,t,n){const r=o=>{n(o),e.removeEventListener(t,r)};e.addEventListener(t,r)}function K(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}async function Q(e){try{return await navigator.clipboard.writeText(e),!0}catch{const t=document.createElement("textarea");if(t.value=e,document.body.appendChild(t),t.select(),!document?.execCommand)return!1;const n=document?.execCommand("copy");return document.body.removeChild(t),n}}function V(e,t="click"){const n=document.querySelectorAll(e);if(n.length===0){console.error(`No elements found for selector ${e}`);return}if(!document.fullscreenEnabled){console.error("Your browser does not support fullscreen mode");return}n.forEach(r=>{r.addEventListener(t,async()=>{try{document.documentElement.requestFullscreen?await document.documentElement.requestFullscreen():"webkitRequestFullscreen"in document.documentElement?document.documentElement.webkitRequestFullscreen():"msRequestFullscreen"in document.documentElement&&document.documentElement.msRequestFullscreen()}catch(o){console.error("Failed to enter fullscreen:",o)}})})}function m(e="local"){return e==="local"?localStorage:sessionStorage}function X(e,t){if(!t)return e;const n=new Date().getTime();return{value:e,expires:n+t}}function Z(e){return!e||typeof e!="object"?e:"expires"in e&&"value"in e?new Date().getTime()>e.expires?null:e.value:e}const ee={get(e,t={}){try{const{storage:n="local"}=t,r=m(n),o=r.getItem(e);if(!o)return null;const i=D(o),u=Z(i);return u===null&&r.removeItem(e),u}catch{return null}},set(e,t,n={}){try{const{storage:r="local",expires:o}=n,i=m(r),u=X(t,o);return i.setItem(e,JSON.stringify(u)),!0}catch{return!1}},remove(e,t={}){const{storage:n="local"}=t;m(n).removeItem(e)},clear(e={}){const{storage:t="local"}=e;m(t).clear()}};function te(e=window.location.search){return e?x.parseUrl(e).query:{}}function ne(e,t){return`${t||window.location.href}${S(e)?"":"?"}${x.stringify(e)}`}async function re(e,t,n={}){try{const r=await fetch(e,n);if(!r.ok)throw new Error(`\u4E0B\u8F7D\u5931\u8D25: HTTP\u72B6\u6001\u7801 ${r.status} ${r.statusText}`);if(!t){const a=r.headers.get("content-disposition");if(a){const s=a.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);s&&s[1]&&(t=s[1].replace(/['"]/g,""))}t||(t=e.split("/").pop()||"downloaded-file")}const o=await r.blob(),i=URL.createObjectURL(o),u=document.createElement("a");u.href=i,u.download=t,document.body.appendChild(u),u.click(),setTimeout(()=>{document.body.removeChild(u),URL.revokeObjectURL(i)},100)}catch(r){throw console.error("\u6587\u4EF6\u4E0B\u8F7D\u5931\u8D25:",r),r instanceof Error?new Error(`\u6587\u4EF6\u4E0B\u8F7D\u5931\u8D25: ${r.message}`):new Error("\u6587\u4EF6\u4E0B\u8F7D\u5931\u8D25: \u53D1\u751F\u672A\u77E5\u9519\u8BEF")}}function oe(e){const t=e.length;for(let n=0;n<t-1;n++)for(let r=0;r<t-1-n;r++)e[r]>e[r+1]&&([e[r],e[r+1]]=[e[r+1],e[r]]);return e}function h(e){if(e.length<=1)return e;const t=e[0],n=e.filter(o=>o<t),r=e.filter(o=>o>t);return[...h(n),t,...h(r)]}function ie(e,t){let n=0,r=e.length-1;for(;n<=r;){const o=Math.floor((n+r)/2);if(e[o]===t)return o;e[o]<t?n=o+1:r=o-1}return-1}function ue(e){if(e<=1)return!1;for(let t=2;t<=Math.sqrt(e);t++)if(e%t===0)return!1;return!0}function ce(e){const t=[0,1];for(let n=2;n<=e;n++)t[n]=t[n-1]+t[n-2];return t[e]}function p(e){return e<0?0:e<=1?e:p(e-1)+p(e-2)}const F=c;F.set({precision:20,rounding:c.ROUND_HALF_UP});function ae(...e){return e.reduce((t,n)=>t.plus(new c(n)),new c(0))}function se(e,t,...n){let r=new c(e).minus(new c(t));for(const o of n)r=r.minus(new c(o));return r}function le(...e){return e.length===0?new c(0):e.reduce((t,n)=>t.times(new c(n)),new c(1))}function b(e,t,...n){let r=new c(e).dividedBy(new c(t));for(const o of n)r=r.dividedBy(new c(o));return r}function fe(e,t=2){if(t<0)throw new Error("Decimal places must be a non-negative integer");return new c(e).toDecimalPlaces(t)}function de(e,t){return new c(e).comparedTo(new c(t))}function me(e,t,n){if(Number(t)===0)return"NaN";const{decimalPlaces:r=2,isSymbol:o=!1}=n||{};return o?`${b(e,t).times(100).toFixed(r)}%`:b(e,t).times(100).toFixed(r)}class we{value;constructor(t){this.value=new c(t)}add(t){return this.value=this.value.plus(new c(t)),this}sub(t){return this.value=this.value.minus(new c(t)),this}mul(t){return this.value=this.value.times(new c(t)),this}div(t){if(Number(t)===0)throw new Error("Cannot divide by zero");return this.value=this.value.dividedBy(new c(t)),this}round(t=2){return this.value.toDecimalPlaces(t)}}function ge(e,t="CNY",n="zh-CN"){if(Number.isNaN(e))throw new Error("Invalid amount");return new Intl.NumberFormat(n,{style:"currency",currency:t}).format(e)}function y(e){if(!/^#(?:[0-9a-f]{6}|[0-9a-f]{8})$/i.test(e))throw new Error("Invalid hex color");const t=Number.parseInt(e.slice(1,3),16),n=Number.parseInt(e.slice(3,5),16),r=Number.parseInt(e.slice(5,7),16),o=e.length>7?Number.parseInt(e.slice(7,9),16)/255:1;return{r:t,g:n,b:r,a:o}}function T({r:e,g:t,b:n,a:r=1}){if(e<0||e>255)throw new Error("Invalid red value");if(t<0||t>255)throw new Error("Invalid green value");if(n<0||n>255)throw new Error("Invalid blue value");if(r<0||r>1)throw new Error("Invalid alpha value");const o=i=>Math.round(i).toString(16).padStart(2,"0");return`#${o(e)}${o(t)}${o(n)}${r<1?o(r*255):""}`}function he(e,t,n){if(!/^#(?:[0-9a-f]{6}|[0-9a-f]{8})$/i.test(e))throw new Error("Invalid hex color");if(n<0||n>1)throw new Error("Invalid t value");const r=y(e),o=y(t);return T({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n,a:r.a+(o.a-r.a)*n})}async function P(e,t={},n=5e3){const r=new AbortController,o=setTimeout(()=>r.abort(),n);try{const i=await fetch(e,{...t,signal:r.signal});return clearTimeout(o),i}catch(i){throw clearTimeout(o),new Error(`\u8BF7\u6C42\u8D85\u65F6\u6216\u5931\u8D25: ${i.message}`)}}async function j(e,t,n,r={}){const o={method:e,headers:{"Content-Type":"application/json",...r}};n&&(o.body=JSON.stringify(n));const i=await P(t,o);if(!i.ok)throw new Error(`HTTP\u9519\u8BEF ${i.status}`);return i.json()}async function pe(e,t=5){const n=[],r=new Set;for(const o of e){const i=o().then(u=>{n.push(u),r.delete(i)});r.add(i),r.size>=t&&await Promise.race(r)}return await Promise.all(r),n}async function be(){try{return(await j("GET","https://api.ipify.org?format=json")).ip}catch{return"unknown"}}async function ye(e,t){const n=await new Promise((r,o)=>{const i=indexedDB.open(e,1);i.onupgradeneeded=()=>{i.result.createObjectStore(t)},i.onsuccess=()=>r(i.result),i.onerror=o});return{async get(r){return new Promise(o=>{const i=n.transaction(t,"readonly").objectStore(t).get(r);i.onsuccess=()=>o(i.result),i.onerror=()=>o(void 0)})},async set(r,o){return new Promise((i,u)=>{const a=n.transaction(t,"readwrite").objectStore(t).put(o,r);a.onsuccess=()=>i(),a.onerror=u})}}}function xe(){return new Promise(e=>{if(navigator.onLine!==void 0)e(navigator.onLine);else{const t=new Image;t.onload=()=>e(!0),t.onerror=()=>e(!1),t.src=`https://www.google.com/favicon.ico?${Date.now()}`}})}function ve(e,t,n){if(n===0)throw new Error("division by zero");return e.map(r=>(r-t)/n)}function Ee(e){const t=Math.min(...e),n=Math.max(...e);return t===n?e.map(()=>0):e.map(r=>(r-t)/(n-t))}function Se(e){if(e.length===1)return e[0];const t=e.length,n=Array.from({length:t},(l,f)=>f),r=e,o=n.reduce((l,f)=>l+f,0)/t,i=r.reduce((l,f)=>l+f,0)/t,u=n.reduce((l,f,C)=>l+(f-o)*(r[C]-i),0),a=n.reduce((l,f)=>l+(f-o)**2,0),s=u/a,w=i-s*o;return s*t+w}export{we as CalculatorChain,ie as binarySearch,oe as bubbleSort,me as calculatePercentage,xe as checkNetworkStatus,de as compare,Q as copyToClipboard,Y as curry,J as dateFormat,_ as dayjs,H as debounce,F as decimal,g as deepClone,re as downloadFile,V as enterFullScreen,P as fetchWithTimeout,ce as fibonacciDP,p as fibonacciRecursive,ge as formatCurrency,be as getClientIP,ye as getIndexedDBCache,I as getTypeName,te as getUrlParams,ne as getUrlParamsString,A as getUuid,y as hexToRgba,R as isBoolean,U as isBrowser,N as isDate,S as isEmptyObject,v as isFunction,K as isMobile,k as isNull,B as isNumber,E as isObject,ue as isPrime,L as isRegExp,O as isString,q as isUndefined,he as lerpColor,Se as linearRegression,G as manageClasses,ve as normalizeData,Ee as normalizeMinMax,$ as numberToFixed,W as onceEventListener,pe as parallelRequests,ae as preciseAdd,b as preciseDiv,le as preciseMul,se as preciseSub,h as quickSort,j as request,T as rgbaToHex,fe as roundTo,D as safeJSONParse,ee as safeStorage,z as throttle,d as toString};