UNPKG

3h-utils

Version:
1 lines 2.31 kB
const insertElement=(e,t,n)=>{if(t<0||t>e.length)throw new RangeError("invalid index to insert");if(0===t)e.unshift(n);else if(t===e.length)e.push(n);else{e.length++;for(let n=e.length-1;n>t;n--)e[n]=e[n-1];e[t]=n}},removeElements=(e,t,n=Math.max(0,e.length-t))=>{if(n<0)throw new RangeError("invalid count");if(t<0||t+n>e.length)throw new RangeError("invalid index to remove");for(let r=t;r<e.length-n;r++)e[r]=e[r+n];e.length-=n},clampIndex=(e,t)=>{if(e<-t||e>=t)throw new RangeError("invalid index");return e<0?e+t:e},pick=e=>{if(0===e.length)throw new RangeError("no elements to pick");return e[Math.floor(e.length*Math.random())]},sort=(e,t)=>{let n;for(let r=0;r<e.length-1;r++)for(let o=r+1;o<e.length;o++)t(e[r],e[o])>0&&(n=e[r],e[r]=e[o],e[o]=n)},shuffle=e=>{let t,n;for(let r=e.length-1;r>0;r--)t=Math.floor(Math.random()*r),n=e[r],e[r]=e[t],e[t]=n},unique=e=>{const t=[];let n;for(let r=0;r<e.length;r++)n=e[r],-1===t.indexOf(n)&&t.push(n);return t},merge=(...e)=>Object.assign(Object.create(null),...e),isDict=e=>"[object Object]"===Object.prototype.toString.call(e),cloneShallowly=e=>Array.isArray(e)?e.map((e=>e)):e&&"object"==typeof e?Object.assign(Object.create(null),e):e,cloneDeeply=e=>{if(Array.isArray(e))return e.map((e=>cloneDeeply(e)));if(e&&"object"==typeof e){const t=Object.create(null);for(const n in e){const r=e[n];t[n]=r&&"object"==typeof r?cloneDeeply(r):r}return t}return e},random=(e,t)=>e+(t-e)*Math.random(),clamp=(e,t,n)=>e<=t?t:e>=n?n:e,interpolate=(e,t,n)=>e+(t-e)*n,deg2rad=e=>e/180*Math.PI,rad2deg=e=>e/Math.PI*180,quadraticSum=(...e)=>e.reduce(((e,t)=>e+t**2),0),throttle=(e,t)=>{let n=null;const throttleWrapper=(...e)=>{const r=Date.now();if(null===n||r-n>=throttleWrapper.throttleGap)return n=r,t(...e)};return throttleWrapper.throttleGap=e,throttleWrapper},debounce=(e,t)=>{let n=null;const debounceWrapper=(...e)=>{null!==n&&clearTimeout(n),n=setTimeout(t,debounceWrapper.debounceTimeout,...e)};return debounceWrapper.debounceTimeout=e,debounceWrapper},lock=e=>{const wrapper=(...t)=>{if(!wrapper.disabled)return wrapper.disabled=!0,e(...t)};return wrapper.disabled=!1,wrapper};export{clamp,clampIndex,cloneDeeply,cloneShallowly,debounce,deg2rad,insertElement,interpolate,isDict,lock,merge,pick,quadraticSum,rad2deg,random,removeElements,shuffle,sort,throttle,unique};