primitiveprimer
Version:
Bluntly extend String, Array, Number, Object prototypes with useful methods, or use them as standalone utilities while leaving prototypes untouched
2 lines • 17.2 kB
JavaScript
;var m=Object.defineProperty;var B=Object.getOwnPropertyDescriptor;var F=Object.getOwnPropertyNames;var L=Object.prototype.hasOwnProperty;var z=(t,r)=>{for(var e in r)m(t,e,{get:r[e],enumerable:!0})},$=(t,r,e,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of F(r))!L.call(t,s)&&s!==e&&m(t,s,{get:()=>r[s],enumerable:!(n=B(r,s))||n.enumerable});return t};var q=t=>$(m({},"__esModule",{value:!0}),t);var X={};z(X,{applyPrimitives:()=>Q,applyPrimitivesGlobally:()=>Q,pkit:()=>A});module.exports=q(X);var a=t=>{if(!(Array.isArray(t)&&t.every(r=>typeof r=="object"&&r!==null)))throw new Error("not an array of objects")},d=t=>{if(!t.every(r=>typeof r=="string"))throw new Error("not an array of strings")},u=t=>{if(!t.every(r=>typeof r=="number"))throw new Error("not an array of numbers")},J=[["filterGuard",function(t){return this.filter(r=>t(r))}],["findGuard",function(t){for(let r of this)if(t(r))return r}],["assertIsStringArray",function(){d(this)}],["assertIsNumberArray",function(){u(this)}],["asStrings",function(){try{return d(this),this}catch{return this}}],["asNumbers",function(){try{return u(this),this}catch{return this}}],["tryAsStrings",function(){try{return d(this),this}catch{return null}}],["tryAsNumbers",function(){try{return u(this),this}catch{return null}}]],b=[["first",function(t=1){return t===1?this[0]:this.slice(0,t)}],["last",function(t=1){return t===1?this[this.length-1]:this.slice(-t)}],["findByKey",function(t,r){a(this);for(let e of this)if(e[t]===r)return e;return null}],["groupBy",function(t){return this.reduce((r,e)=>{let n=typeof t=="function"?t(e):e[t];return(r[n]||=[]).push(e),r},{})}],["sumByKey",function(t){return a(this),this.reduce((r,e)=>r+(typeof e[t]=="number"?e[t]:0),0)}],["autoParseKeys",function(){return a(this),this.map(t=>{if(t&&typeof t=="object"){for(let r in t)if(typeof t[r]=="string")try{t[r]=JSON.parse(t[r])}catch{}}return t})}],["unique",function(){return[...new Set(this)]}],["shuffle",function(){let t=[...this];for(let r=t.length-1;r>0;r--){let e=Math.floor(Math.random()*(r+1));[t[r],t[e]]=[t[e],t[r]]}return t}],["highestByKey",function(t){try{return a(this),u(this.map(r=>r[t])),this.length,this.reduce((r,e)=>typeof e[t]=="number"&&e[t]>(r?.[t]??-1/0)?e:r)}catch(r){return console.error("not an numberarray in object",r),-1}}],["lowestByKey",function(t){try{return a(this),u(this.map(r=>r[t])),this.reduce((r,e)=>typeof e[t]=="number"&&e[t]<(r?.[t]??1/0)?e:r)}catch(r){return console.error("not an objectArray",r),-1}}],["sortByKey",function(t,r=!0){try{return a(this),[...this].sort((e,n)=>{let s=e[t]??0,i=n[t]??0;return r?s-i:i-s})}catch(e){return console.error("not an objectArray",e),[]}}],["sortByKeyName",function(t,r=!0){try{return a(this),[...this].sort((e,n)=>{let s=String(e[t]??""),i=String(n[t]??"");return r?s.localeCompare(i):i.localeCompare(s)})}catch(e){return console.error("not an objectArray",e),[]}}],["mapByKey",function(t){return a(this),this.map(r=>r&&typeof r=="object"?r[t]:void 0)}],["sumKey",function(t){try{return a(this),u(this.map(r=>r[t])),this.reduce((r,e)=>r+(parseFloat(String(e[t]))||0),0)}catch(r){return console.error("not an numberarray in object",r),0}}],["averageKey",function(t){try{a(this),u(this.map(n=>n[t]));let r=0,e=0;for(let n of this){let s=parseFloat(String(n[t]));Number.isNaN(s)||(r+=s,e++)}return e?r/e:0}catch(r){return console.error("not an numberarray in object",r),0}}],["filterKey",function(t,r){try{return a(this),this.filter(e=>r(e[t]))}catch(e){return console.error("not an objectArray",e),[]}}],["distinct",function(t){try{a(this);let r=new Set,e=typeof t=="function"?t:s=>s[t],n=[];for(let s of this){let i=e(s);r.has(i)||(r.add(i),n.push(s))}return n}catch(r){return console.error("not an objectArray",r),[]}}],["aggregate",function(t,r,e){try{a(this);let n=typeof t=="function"?t:o=>o[t],s=new Map;for(let o of this){let c=n(o),l=s.has(c)?s.get(c):e;s.set(c,r(l,o))}let i={};for(let[o,c]of s.entries())i[o]=c;return i}catch(n){return console.error("not an objectArray",n),{}}}],["toTable",function(){try{a(this);let t={};for(let r of this)for(let[e,n]of Object.entries(r))(t[e]??=[]).push(n);return t}catch(t){return console.error("not an objectArray",t),{}}}],["sumBy",function(t){try{return a(this),u(this.map(r=>r[t])),this.reduce((r,e)=>{let n=parseFloat(String(e[t]));return r+(Number.isNaN(n)?0:n)},0)}catch(r){return console.error("not an objectArray",r),0}}],["averageBy",function(t){try{a(this),u(this.map(n=>n[t]));let r=0,e=0;for(let n of this){let s=parseFloat(String(n[t]));Number.isNaN(s)||(r+=s,e++)}return e?r/e:0}catch(r){return console.error("not an objectArray",r),0}}],["seededShuffle",function(t){let r=[...this],e=this.length,n=Array.from({length:e},(o,c)=>c),s=()=>(t=1103515245*t+12345>>>0)/4294967295;for(let o=e-1;o>0;o--){let c=Math.floor(s()*(o+1));[n[o],n[c]]=[n[c],n[o]]}return n.map(o=>r[o])}],["intersect",function(t){let r=new Set(t);return this.filter(e=>r.has(e))}],["difference",function(t){let r=new Set(t);return this.filter(e=>!r.has(e))}],["sum",function(){try{u(this);let t=0;for(let r of this){let e=typeof r=="number"?r:parseFloat(String(r));Number.isNaN(e)?r&&(t+=1):t+=e}return t}catch(t){return console.error("not an array of numbers",t),0}}],["average",function(){try{u(this);let t=0,r=0;for(let e of this){let n=typeof e=="number"?e:parseFloat(String(e));Number.isNaN(n)?e&&(t+=1,r++):(t+=n,r++)}return r===0?0:t/r}catch(t){return console.error("not an array of numbers",t),0}}],["validateEach",function(t){return this.map(r=>r!=null&&t(r)?r:null)}],["clearNil",function(){return this.filter(t=>t!=null)}],["indexOfHighestNumber",function(){try{if(u(this),this.length===0)return-1;let t=0;for(let r=1;r<this.length;r++)this[r]>this[t]&&(t=r);return t}catch(t){return console.error("not an array of numbers",t),-1}}],["indexOfLowestNumber",function(){try{if(u(this),this.length===0)return-1;let t=0;for(let r=1;r<this.length;r++)this[r]<this[t]&&(t=r);return t}catch(t){return console.error("not an array of numbers",t),-1}}]];function O(){for(let t of b)Object.defineProperty(Array.prototype,t[0],{value:t[1],writable:!0,configurable:!0,enumerable:!1});for(let t of J)Object.defineProperty(Array.prototype,t[0],{value:t[1],writable:!0,configurable:!0,enumerable:!1})}var p=[["percentage",function(t){return this*t/100}],["isEven",function(){return this%2===0}],["isOdd",function(){return this%2!==0}],["toFixedNumber",function(t=2){return parseFloat(this.toFixed(t))}],["between",function(t,r){return this>=t&&this<=r}],["assertNrBetween",function(t=0,r=1/0){return this>=t&&this<=r}],["clamp",function(t,r){return Math.min(Math.max(this,t),r)}],["times",function(t){for(let r=0;r<this;r++)t(r)}],["toStringWithLeadingZeros",function(t){return String(this).padStart(t,"0")}],["toTimeCode",function(){let t=Math.floor(this),r=Math.floor(t/3600),e=Math.floor(t%3600/60),n=t%60;return`${r}:${e.toStringWithLeadingZeros(2)}:${n.toStringWithLeadingZeros(2)}`}],["percentOf",function(t){return t===0?0:this/t*100}],["ratioOf",function(t){return t===0?0:this/t}],["isInteger",function(){return Number.isInteger(this)}],["isFinite",function(){return Number.isFinite(this)}],["isSafeInteger",function(){return Number.isSafeInteger(this)}],["isPositive",function(){return this>0}],["isNegative",function(){return this<0}],["isNonNegative",function(){return this>=0}],["assertIsInteger",function(){if(!Number.isInteger(this))throw new Error("Not an integer")}],["assertIsFinite",function(){if(!Number.isFinite(this))throw new Error("Not finite (NaN or Infinity)")}]];function M(){for(let t of p)Object.defineProperty(Number.prototype,t[0],{value:t[1],writable:!0,configurable:!0})}var T=[["sortKeys",function(t=null){return Object.fromEntries(Object.entries(this).sort(([r],[e])=>t?t(r,e):r.localeCompare(e)))}],["fill",function(t){for(let[r,e]of Object.entries(t))r in this||(this[r]=e);return this}],["parseKeys",function(...t){let r=this.valueOf(),e={};for(let n of t)try{e[n]=JSON.parse(r[n])}catch{e[n]=r[n]}return r}],["valuesMap",function(t){return Object.fromEntries(Object.entries(this).map(([r,e])=>[r,t(e,r)]))}],["entriesMap",function(t){return Object.fromEntries(Object.entries(this).map(t))}],["keysMap",function(t){return Object.fromEntries(Object.entries(this).map(([r,e])=>t(r,e)))}],["equals",function(t){let r=Object.keys(this),e=Object.keys(t);return r.length!==e.length?!1:r.every(n=>e.includes(n)&&typeof this[n]==typeof t[n])}],["omit",function(...t){let r={};for(let e of Object.keys(this))t.includes(e)||(r[e]=this[e]);return r}],["pick",function(...t){let r={};for(let e of t)e in this&&(r[e]=this[e]);return r}],["complement",function(t){let r={...this};for(let e of Object.keys(t))e in r||(r[e]=t[e]);return r}],["clean",function(){let t={};for(let[r,e]of Object.entries(this))e===""||e==null||(t[r]=e);return t}],["ensureSchema",function(t,r={}){let e={};for(let[n,s]of Object.entries(t)){let i=this[n];if(i==null&&(i=s),r.coerce){let o=typeof s;o==="number"?i=Number(i):o==="boolean"?i=!!i:o==="string"&&(i=String(i))}e[n]=i}return e}],["filterEntries",function(t){let r={};for(let[e,n]of Object.entries(this))t(e,n)&&(r[e]=n);return r}],["merge",function(t,r={}){let e={...this};for(let[n,s]of Object.entries(t)){let i=e[n];if(Array.isArray(i)&&Array.isArray(s)){let o=r.arrayStrategy??"concat";o==="replace"?e[n]=s:o==="unique"?e[n]=Array.from(new Set([...i,...s])):e[n]=[...i,...s]}else i&&typeof i=="object"&&s&&typeof s=="object"?e[n]={...i,...s}:e[n]=s}return e}],["fromTable",function(){let t=Object.keys(this),r=Math.max(0,...t.map(n=>this[n]?.length??0)),e=Array.from({length:r},()=>({}));for(let n of t){let s=this[n]||[];for(let i=0;i<r;i++)e[i][n]=s[i]}return e}]];function j(){for(let t of T)Object.defineProperty(Object.prototype,t[0],{value:t[1],writable:!0,configurable:!0,enumerable:!1})}function H(t,r,e="Type assertion failed"){if(!r(t))throw new Error(e)}var R=[["assertNonEmptyString",function(){try{return H(this,t=>typeof t=="string"),this}catch{return!1}}],["isNonEmty",function(){return typeof this=="string"&&this.trim().length>0}],["changeExtension",function(t){return this.replace(/\.[0-9a-z]{1,5}$/i,"."+t.replace(/\W/,"").substring(0,5))}],["reverse",function(){return this.split("").reverse().join("")}],["toTitleCase",function(){return this.replace(/\w\S*/g,t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase())}],["words",function(){return this.match(/\b\w+\b/g)||[]}],["slashreverse",function(t){return t.replace(/[\\/]/g,r=>r==="\\"?"/":"\\")}],["slashwin",function(){return this.replace(/[\\/]/g,"\\")}],["slashlinux",function(){return this.replace(/[\\/]/g,"/")}],["strip",function(){return this.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/\s+/g,"").trim()}],["containsAny",function(...t){return t.some(r=>this.includes(r))}],["toSlug",function(){return this.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/\s+/g,"-").replace(/[^\w-]/g,"").replace(/--+/g,"-").replace(/^-+|-+$/g,"")}],["stripCompare",function(t){let r=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\s_]/g,"").trim();return r(this).includes(r(t))}],["toWordCapitalized",function(){return this?this.charAt(0).toUpperCase()+this.slice(1).toLowerCase():""}],["truncate",function(t,r="\u2026"){return this.length>t?this.slice(0,t)+r:this.toString()}],["isJson",function(){try{return JSON.parse(this),!0}catch{return!1}}],["toCamelCase",function(){return this.replace(/([-_][a-z])/gi,t=>t.toUpperCase().replace("-","").replace("_",""))}],["safeParseJson",function(){try{return JSON.parse(this)}catch{return this.valueOf()}}],["nullParseJson",function(){if(!this.trim())return null;try{return JSON.parse(this)}catch{return null}}],["filenameCompare",function(t){let r=e=>e.replace(/\\/g,"/").split("/").pop()?.toLowerCase()??"";return r(this)===r(t)}],["substringFrom",function(t,r){let e=String(this);if(!t)return e;let n=e.indexOf(t);if(n===-1)return"";let s=n+t.length;if(!r)return e.slice(s);let i=e.indexOf(r,s);return i===-1?e.slice(s):e.slice(s,i)}],["escapeHTML",function(){return this.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\"/g,""").replace(/'/g,"'")}],["unescapeHTML",function(){return this.replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/&/g,"&")}],["humanize",function(){return this.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[\-_]+/g," ").replace(/\s{2,}/g," ").trim().replace(/(^\w|[.!?]\s+\w)/g,r=>r.toUpperCase())}],["underscore",function(){return this.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[\s\-]+/g,"_").toLowerCase()}],["countOccurrence",function(t,r=!0){let e=r?this:this.toLowerCase(),n=r?t:t.toLowerCase();if(!n)return 0;let s=0,i=0;for(;(i=e.indexOf(n,i))!==-1;)s++,i+=n.length;return s}],["isNumber",function(){return/^\s*[+-]?(?:\d+\.?\d*|\.\d+)\s*$/.test(this)}],["isFloat",function(){return/^\s*[+-]?\d*\.\d+\s*$/.test(this)&&!Number.isNaN(parseFloat(this))}],["isAlphaNumeric",function(){return/^[a-z0-9]+$/i.test(this)}],["isLower",function(){return this===this.toLowerCase()&&/[a-z]/.test(this)}],["isUpper",function(){return this===this.toUpperCase()&&/[A-Z]/.test(this)}],["hashed",function(t){let r=5381;for(let n=0;n<this.length;n++)r=(r<<5)+r+this.charCodeAt(n);let e=(r>>>0).toString(16);return typeof t=="number"?e.slice(0,Math.max(0,t)):e}],["replaceLast",function(t,r){let e=String(this);if(t instanceof RegExp){let n=e.match(t);if(!n)return e;let s=n[n.length-1],i=e.lastIndexOf(s);return i===-1?e:e.slice(0,i)+r+e.slice(i+s.length)}else{let n=e.lastIndexOf(t);return n===-1?e:e.slice(0,n)+r+e.slice(n+t.length)}}],["latinise",function(){return this.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}],["ellipsis",function(t){return t<=3?this.slice(0,t):this.length>t?this.slice(0,t-3)+"...":this}],["toNumber",function(){let r=this.replace(/[^0-9+\-\.eE]/g," ").match(/[+\-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+\-]?\d+)?/);return r?Number(r[0]):NaN}],["toBoolean",function(){let t=this.trim().toLowerCase();return["1","true","yes","on","y"].includes(t)?!0:["0","false","no","off","n"].includes(t)?!1:!!t}]];function N(){for(let t of R)Object.defineProperty(String.prototype,t[0],{value:t[1],writable:!0,configurable:!0})}var f={randomRangeFloat(t,r){return Math.random()*(r-t)+t},randomRangeInt(t,r){return Math.floor(Math.random()*(r-t+1))+t},lerp(t,r,e){return t+(r-t)*e},clamp(t,r,e){return Math.min(Math.max(t,r),e)},degToRad(t){return t*(Math.PI/180)},radToDeg(t){return t*(180/Math.PI)},distance(t,r,e,n){return Math.hypot(e-t,n-r)},roundTo(t,r=2){return Math.round(t*10**r)/10**r},isPowerOfTwo(t){return t>0&&(t&t-1)===0},nextPowerOfTwo(t){return 2**Math.ceil(Math.log2(t))},normalize(t,r,e){return(t-r)/(e-r)},smoothStep(t,r,e){let n=Math.max(0,Math.min(1,(e-t)/(r-t)));return n*n*(3-2*n)},mix(t,r,e){return t*(1-e)+r*e},mixColors(t,r,e){let n=g=>g.replace("#","").padStart(6,"0"),[s,i]=[n(t),n(r)],[o,c,l]=[parseInt(s.slice(0,2),16),parseInt(s.slice(2,4),16),parseInt(s.slice(4,6),16)],[K,v,P]=[parseInt(i.slice(0,2),16),parseInt(i.slice(2,4),16),parseInt(i.slice(4,6),16)],I=Math.round(this.mix(o,K,e)),U=Math.round(this.mix(c,v,e)),C=Math.round(this.mix(l,P,e)),y=g=>g.toString(16).padStart(2,"0");return`#${y(I)}${y(U)}${y(C)}`}};function w(){globalThis.mathUtils||(globalThis.mathUtils=f),typeof globalThis.window<"u"&&Object.assign(globalThis.window,{mathUtils:f})}var k=t=>{if(typeof t=="string")return _(t);if(typeof t=="number")return W(t);if(Array.isArray(t))return Z(t);if(t&&typeof t=="object")return D(t);if(t===null)return!1;if(typeof t>"u")return null;if(typeof t=="function")return k(t())};function _(t){let r=t;return Object.fromEntries(R.map(([e,n])=>[e,function(...s){return r=n.apply(r,s),r}]))}function W(t){let r=t,e;return Object.fromEntries(p.map(([n,s])=>[n,function(...i){return e=s.apply(r,i),e}]))}function Z(t){let r=t,e=null;return Object.fromEntries(b.map(([n,s])=>[n,function(...i){return e=s.apply(r,i),e}]))}function D(t){let r=t;return Object.fromEntries(T.map(([e,n])=>[e,function(...s){return r=n.apply(r,s),r}]))}var h=t=>t.replace(/\\/g,"/").replace(/\/{2,}/g,"/"),E=globalThis.process?globalThis.process.platform==="win32"?"\\":"/":globalThis.window?.navigator.platform.startsWith("Win")?"\\":"/",V={sep:E,normalize:h,join:(...t)=>h(t.filter(Boolean).join(E)),basename:t=>h(t).split("/").pop()||"",dirname:t=>{let r=h(t).split("/");return r.pop(),r.length?r.join("/"):"."},extname:t=>{let r=h(t).split("/").pop()||"",e=r.lastIndexOf(".");return e>0?r.slice(e):""}},x=k;x.math=f;x.path=V;var A=x;function G(){let t=e=>e.replace(/\\/g,"/").replace(/\/{2,}/g,"/");return{sep:"/",normalize:t,join:(...e)=>t(e.filter(Boolean).join("/")),basename:e=>t(e).split("/").pop()||"",dirname:e=>{let n=t(e).split("/");return n.pop(),n.length?n.join("/"):"."},extname:e=>{let n=t(e).split("/").pop()||"",s=n.lastIndexOf(".");return s>0?n.slice(s):""}}}function S(){typeof globalThis>"u"||globalThis.path||(globalThis.path=G())}function Q(){N(),O(),M(),j(),S(),w()}0&&(module.exports={applyPrimitives,applyPrimitivesGlobally,pkit});
//# sourceMappingURL=primitiveprimer.cjs.map