funtool
Version:
A modern, efficient, and modular JavaScript utility library designed to enhance developer productivity.
3 lines (2 loc) • 9.91 kB
JavaScript
;class e{constructor(n,t){if(n){if(!e.isValid(n))throw new Error("Invalid ObjectId hex string.");this.hex=n.toLowerCase()}else this.hex=function(e=Math.random){return(Math.floor(Date.now()/1e3).toString(16).padStart(8,"0")+Array.from({length:16},(()=>Math.floor(16*e()).toString(16))).join("")).slice(0,24)}(t)}static isValid(e){return"string"==typeof e&&/^[a-fA-F0-9]{24}$/.test(e)}static createFromHexString(n){return new e(n)}static createWithPrefix(n){return n+(new e).toHexString()}toHex(){return this.hex}toBuffer(){const e=new Uint8Array(12);for(let n=0;n<12;n++)e[n]=parseInt(this.hex.slice(2*n,2*n+2),16);return e}equals(e){return this.hex===e.hex}static parse(n,t=!1){if(t){if(!e.isValid(n))throw new Error(`Invalid strict ObjectId: ${n}`);return new e(n)}const r=n.match(/[a-fA-F0-9]{24}/);if(!r)throw new Error(`Invalid format for ObjectId: ${n}`);return new e(r[0])}toHexString(){return this.hex}toUUIDString(){const e=this.hex.padEnd(32,"0");return[e.slice(0,8),e.slice(8,12),e.slice(12,16),e.slice(16,20),e.slice(20)].join("-")}toString(){return this.toHexString()}toBase64(){return Buffer.from(this.toBuffer()).toString("base64")}short(e=""){return e+this.toBase64().replace(/=+$/,"")}getTimestamp(){return 1e3*parseInt(this.hex.slice(0,8),16)}compare(e){return this.hex.localeCompare(e.hex)}clone(){return new e(this.hex)}toJSON(){return this.toHexString()}}function n(e){const[n,t]=e.split(",");if(!n||!t)throw new Error("Invalid base64 format");const r=n.match(/:(.*?);/),o=r?.[1]||"application/octet-stream",i=o.split("/")[1]||"bin",a=atob(t),l=Uint8Array.from(a,(e=>e.charCodeAt(0)));return{blob:new Blob([l],{type:o}),mime:o,ext:i}}const t=[{name:"Edge (Chromium)",regex:/Edg\/([\d.]+)/},{name:"Edge (Legacy)",regex:/Edge\/([\d.]+)/},{name:"Opera",regex:/OPR\/([\d.]+)/},{name:"Vivaldi",regex:/Vivaldi\/([\d.]+)/},{name:"Chrome",regex:/Chrome\/([\d.]+)/},{name:"Firefox",regex:/Firefox\/([\d.]+)/},{name:"Safari",regex:/Version\/([\d.]+).*Safari/},{name:"Internet Explorer",regex:/MSIE ([\d.]+);/},{name:"Internet Explorer",regex:/Trident\/7.0.*rv:([\d.]+)/},{name:"Samsung Internet",regex:/SamsungBrowser\/([\d.]+)/}],r=[{name:"Windows",regex:/Windows NT ([\d.]+)/},{name:"macOS",regex:/Mac OS X ([\d_]+)/,versionReplace:/_/g},{name:"iOS",regex:/\(iP(?:hone|ad|od); CPU (?:iPhone )?OS ([\d_]+)/,versionReplace:/_/g},{name:"Android",regex:/Android ([\d.]+)/},{name:"Linux",regex:/Linux/},{name:"Chrome OS",regex:/CrOS [\w\d_]+ ([\d.]+)/},{name:"Windows Phone",regex:/Windows Phone ([\d.]+)/}],o=[{type:"Mobile",regex:/Mobile|iPhone|Android/},{type:"Tablet",regex:/Tablet|iPad/},{type:"SmartTV",regex:/SmartTV|SMART-TV|Smart-TV|NetCast.TV|AppleTV|Roku/},{type:"Console",regex:/Xbox|PlayStation/},{type:"Wearable",regex:/Watch|Wearable/}],i=[{name:"Blink",regex:/Chrome\/([\d.]+)/},{name:"WebKit",regex:/AppleWebKit\/([\d.]+)/},{name:"Gecko",regex:/Gecko\/([\d.]+)/},{name:"Trident",regex:/Trident\/([\d.]+)/},{name:"EdgeHTML",regex:/EdgeHTML\/([\d.]+)/}];function a(e){const n=e||("undefined"!=typeof navigator?navigator.userAgent:""),a={browser:{name:null,version:null,majorVersion:null},os:{name:null,version:null,majorVersion:null},device:{type:"Unknown",model:null,vendor:null},engine:{name:null,version:null},originalUA:n};for(const{name:e,regex:r}of t){const t=n.match(r);if(t){const n=t[1];a.browser={name:e,version:n,majorVersion:n?.split(".")[0]??null};break}}for(const{name:e,regex:t,versionReplace:o}of r){const r=n.match(t);if(r){let n=r[1]||null;n&&o&&(n=n.replace(o,".")),a.os={name:e,version:n,majorVersion:n?.split(".")[0]??null};break}}for(const{name:e,regex:t}of i){const r=n.match(t);if(r){a.engine={name:e,version:r[1]||null};break}}for(const{type:e,regex:t}of o)if(t.test(n)){a.device.type=e,/iPhone/.test(n)?a.device.model="iPhone":/iPad/.test(n)?a.device.model="iPad":/Android/.test(n)&&(a.device.model="Android Device");break}return"Unknown"===a.device.type&&(a.device.type="Desktop"),a}exports.ObjectId=e,exports.awaitTo=function(e){var n;return(null!==(n=e)&&"object"==typeof n&&"function"==typeof n.then?e:Promise.resolve(e)).then((e=>[null,e])).catch((e=>[e,void 0]))},exports.base64ToBlob=n,exports.base64ToFormData=function(e,t){const{blob:r,ext:o}=n(e),i=t?.key||"file";let a=t?.filename;a?a.includes(".")||(a+=`.${o}`):a=`${Date.now()}.${o}`;const l=new FormData;return l.append(i,r,a),l},exports.currying=function(e){const{fn:n,done:t}=e;return function e(r=[]){const o=(...o)=>{const i=[...r,...o];return t&&t(i)?n(...i):e(i)};return o.map=n=>e(r.map(n)),o.filter=n=>e(r.filter(n)),o.value=()=>n(...r),o.valueOf=()=>o.value(),o.toString=()=>String(o.value()),o}()},exports.debounce=function(e,n=500){let t=null,r=null,o=null,i=null,a=null;const l=()=>{if(r)try{const n=e.apply(o,r);return i?.(n),s(),n}catch(e){throw a?.(e),s(),e}},s=()=>{t=null,r=null,o=null,i=null,a=null};function c(...e){return t&&clearTimeout(t),r=e,o=this,new Promise(((e,r)=>{i=e,a=r,t=setTimeout((()=>{l()}),n)}))}return c.cancel=function(){t&&clearTimeout(t),a?.("Debounced call canceled"),s()},c.flush=function(){return t&&clearTimeout(t),Promise.resolve(l())},c.pending=function(){return!!t},c},exports.debounceSync=function(e,n=500){let t=null,r=null,o=null;const i=()=>{t=null,r=null,o=null},a=()=>{if(r)try{const n=e.apply(o,r);return i(),n}catch(e){throw i(),e}};function l(...e){t&&clearTimeout(t),r=e,o=this,t=setTimeout((()=>{a()}),n)}return l.cancel=()=>{t&&clearTimeout(t),i()},l.flush=()=>(t&&clearTimeout(t),a()),l.pending=()=>!!t,l},exports.generateVerificationCode=function(e=4,n){if(e<=0)return"";const t=/[0Ool1]/g;let r=n?.charset||"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";if(!1!==n?.excludeConfusing&&(r=r.replace(t,"")),!r)throw new Error("Character set is empty after removing confusing characters.");return Array.from({length:e},(()=>{const e=Math.floor(Math.random()*r.length);return r.charAt(e)})).join("")},exports.getBrowserType=function(){const e=a();if(!e.browser.name||!e.browser.version)return null;const n=e.browser.name.toLowerCase(),t=parseInt(e.browser.majorVersion||"0");switch(n){case"internet explorer":return t>=7&&t<=10?`IE${t}`:11===t?"IE11":null;case"edge (chromium)":case"edge (legacy)":return"Edge";case"firefox":return"FireFox";case"opera":return"Opera";case"chrome":return"Chrome";case"safari":return"Safari";default:return null}},exports.getUA=function(e){return void 0!==e?e:"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""},exports.noop=function(){},exports.parseQuery=e=>"object"!=typeof e||null==e?"":Object.keys(e).map((n=>{const t=e[n];return null==t?"":`${encodeURIComponent(n)}=${encodeURIComponent(t)}`})).filter(Boolean).join("&"),exports.parseQueryDeep=e=>{const n=(e,t)=>null==e?[]:"object"!=typeof e||Array.isArray(e)?Array.isArray(e)?e.flatMap((e=>n(e,`${t}[]`))):[`${t}=${encodeURIComponent(String(e))}`]:Object.keys(e).flatMap((r=>n(e[r],`${t}[${encodeURIComponent(r)}]`)));return"object"!=typeof e||null==e?"":Object.keys(e).flatMap((t=>n(e[t],encodeURIComponent(t)))).join("&")},exports.parseQueryDeepWith=(e,n)=>{const t=(e,r)=>{if(null==e)return[];if("object"==typeof e&&!Array.isArray(e))return Object.keys(e).flatMap((n=>t(e[n],[...r,n])));if(Array.isArray(e))return e.flatMap(((e,n)=>t(e,[...r,String(n)])));return[`${n(r.map(encodeURIComponent))}=${encodeURIComponent(String(e))}`]};return"object"!=typeof e||null==e?"":Object.keys(e).flatMap((n=>t(e[n],[n]))).join("&")},exports.parseQueryWith=(e,n)=>"object"!=typeof e||null==e?"":Object.entries(e).map((([e,t])=>n(e,t))).filter((e=>"string"==typeof e)).join("&"),exports.parseUA=a,exports.randomFloat=function(e=0,n=1){return Math.random()*(n-e)+e},exports.randomInt=function(e=0,n=1){return Math.floor(Math.random()*(n-e))+e},exports.throttle=function(e,n=500){let t=null,r=null,o=null,i=null,a=null;const l=()=>{t=Date.now();const n=e.apply(i,o);return a?.(n),s(),n},s=()=>{r=null,o=null,i=null,a=null};function c(...e){const s=Date.now(),c=t?n-(s-t):0;return o=e,i=this,new Promise((e=>{a=e,c<=0?l():r||(r=setTimeout(l,c))}))}return c.cancel=()=>{r&&clearTimeout(r),s()},c.flush=()=>r?(clearTimeout(r),Promise.resolve(l())):Promise.resolve(void 0),c.pending=()=>Boolean(r),c},exports.throttleSync=function(e,n=500){let t=null,r=null,o=null,i=null;const a=()=>{t=Date.now(),e.apply(i,o),l()},l=()=>{r=null,o=null,i=null};function s(...e){const l=Date.now(),s=t?n-(l-t):0;o=e,i=this,s<=0?a():r||(r=setTimeout(a,s))}return s.cancel=()=>{r&&clearTimeout(r),l()},s.flush=()=>{r&&(clearTimeout(r),a())},s.pending=()=>Boolean(r),s},exports.urlParse=function(e){const[n,t]=e.split("#"),[r,o]=n.split("?");let i="",a="",l="/";const s=r.match(/^([a-zA-Z]+:)?\/\//);if(s){i=s[1]||"";const e=r.slice(i.length+2),n=e.indexOf("/");n>=0?(a=e.slice(0,n),l=e.slice(n)||"/"):(a=e,l="/")}else l=r||"/";let c=a,u="";const p=a.indexOf(":");p>=0&&(c=a.slice(0,p),u=a.slice(p+1));const m=i+"//"+a,f={};if(o){const e=o.split("&");for(const n of e){if(!n)continue;const[e,t]=n.split("="),r=decodeURIComponent(e||"").trim();if(!r)continue;const o=void 0!==t?decodeURIComponent(t).trim():"";let i;i=/^\d+(\.\d+)?$/.test(o)?Number(o):"true"===o||"false"!==o&&o,f.hasOwnProperty(r)?Array.isArray(f[r])?f[r].push(i):f[r]=[f[r],i]:f[r]=i}}return{host:a,hostname:c,pathname:l,port:u,protocol:i,origin:m,href:e,search:o?`?${o}`:"",hash:t?`#${decodeURIComponent(t)}`:"",query:f}},exports.urlStringify=function(e){const{protocol:n="",hostname:t,port:r="",pathname:o="/",query:i={},hash:a=""}=e,l=n?n.endsWith(":")?n:`${n}:`:"",s=r?`${t}:${r}`:t,c=o.startsWith("/")?o:`/${o}`,u=Object.entries(i).flatMap((([e,n])=>{if(!e||null==n)return[];const t=e=>encodeURIComponent(String(e));return Array.isArray(n)?n.map((n=>`${encodeURIComponent(e)}=${t(n)}`)):`${encodeURIComponent(e)}=${t(n)}`})).join("&");return`${l}//${s}${c}${u?`?${u}`:""}${a?a.startsWith("#")?a:`#${a}`:""}`};
//# sourceMappingURL=index.cjs.js.map