diff --git a/cdn/radash.esm.js b/cdn/radash.esm.js index ea5cd5e2..1edb270e 100644 --- a/cdn/radash.esm.js +++ b/cdn/radash.esm.js @@ -697,6 +697,15 @@ const keys = (value) => { }; return getKeys(value, []); }; +const crush = (value) => { + if (!value) + return {}; + return objectify( + keys(value), + (k) => k, + (k) => get(value, k) + ); +}; const random = (min, max) => { return Math.floor(Math.random() * (max - min + 1) + min); @@ -835,4 +844,4 @@ const trim = (str, charsToTrim = " ") => { return str.replace(regex, ""); }; -export { alphabetical, assign, boil, callable, camel, capitalize, chain, clone, cluster, compose, counting, dash, debounce, defer, diff, draw, first, flat, fork, get, group, intersects, invert, isArray, isDate, isEmpty, isEqual, isFloat, isFunction, isInt, isNumber, isObject, isPrimitive, isString, isSymbol, iterate, keys, last, list, listify, lowerize, map, mapEntries, mapKeys, mapValues, max, memo, merge, min, objectify, omit, parallel, partial, partob, pascal, pick, proxied, random, range, reduce, replace, replaceOrAppend, retry, select, series, shake, shift, shuffle, sift, sleep, snake, sort, sum, template, throttle, title, toFloat, toInt, toggle, trim, tryit as try, tryit, uid, unique, upperize, zip, zipToObject }; +export { alphabetical, assign, boil, callable, camel, capitalize, chain, clone, cluster, compose, counting, crush, dash, debounce, defer, diff, draw, first, flat, fork, get, group, intersects, invert, isArray, isDate, isEmpty, isEqual, isFloat, isFunction, isInt, isNumber, isObject, isPrimitive, isString, isSymbol, iterate, keys, last, list, listify, lowerize, map, mapEntries, mapKeys, mapValues, max, memo, merge, min, objectify, omit, parallel, partial, partob, pascal, pick, proxied, random, range, reduce, replace, replaceOrAppend, retry, select, series, shake, shift, shuffle, sift, sleep, snake, sort, sum, template, throttle, title, toFloat, toInt, toggle, trim, tryit as try, tryit, uid, unique, upperize, zip, zipToObject }; diff --git a/cdn/radash.js b/cdn/radash.js index f9348b7f..82616263 100644 --- a/cdn/radash.js +++ b/cdn/radash.js @@ -700,6 +700,15 @@ var radash = (function (exports) { }; return getKeys(value, []); }; + const crush = (value) => { + if (!value) + return {}; + return objectify( + keys(value), + (k) => k, + (k) => get(value, k) + ); + }; const random = (min, max) => { return Math.floor(Math.random() * (max - min + 1) + min); @@ -849,6 +858,7 @@ var radash = (function (exports) { exports.cluster = cluster; exports.compose = compose; exports.counting = counting; + exports.crush = crush; exports.dash = dash; exports.debounce = debounce; exports.defer = defer; diff --git a/cdn/radash.min.js b/cdn/radash.min.js index 0698a0d2..ea876fbb 100644 --- a/cdn/radash.min.js +++ b/cdn/radash.min.js @@ -1 +1 @@ -var radash=function(s){"use strict";const _=t=>!!t&&t.constructor===Symbol,b=t=>!!t&&t.constructor===Array,k=t=>!!t&&t.constructor===Object,j=t=>t==null||typeof t!="object"&&typeof t!="function",y=t=>!!(t&&t.constructor&&t.call&&t.apply),M=t=>typeof t=="string"||t instanceof String,D=t=>h(t)&&t%1===0,F=t=>h(t)&&t%1!==0,h=t=>{try{return Number(t)===t}catch{return!1}},z=t=>Object.prototype.toString.call(t)==="[object Date]",R=t=>{if(t===!0||t===!1||t==null)return!0;if(h(t))return t===0;if(z(t))return isNaN(t.getTime());if(y(t)||_(t))return!1;const e=t.length;if(h(e))return e===0;const n=t.size;return h(n)?n===0:Object.keys(t).length===0},P=(t,e)=>{if(Object.is(t,e))return!0;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(t instanceof RegExp&&e instanceof RegExp)return t.toString()===e.toString();if(typeof t!="object"||t===null||typeof e!="object"||e===null)return!1;const n=Reflect.ownKeys(t),r=Reflect.ownKeys(e);if(n.length!==r.length)return!1;for(let i=0;it.reduce((n,r)=>{const i=e(r);return n[i]||(n[i]=[]),n[i].push(r),n},{});function q(...t){return!t||!t.length?[]:new Array(Math.max(...t.map(({length:e})=>e))).fill([]).map((e,n)=>t.map(r=>r[n]))}function I(t,e){if(!t||!t.length)return{};const n=y(e)?e:b(e)?(r,i)=>e[i]:(r,i)=>e;return t.reduce((r,i,u)=>(r[i]=n(i,u),r),{})}const O=(t,e)=>!t||(t.length??0)===0?null:t.reduce(e),U=(t,e)=>(t||[]).reduce((n,r)=>n+(e?e(r):r),0),K=(t,e=void 0)=>t?.length>0?t[0]:e,v=(t,e=void 0)=>t?.length>0?t[t.length-1]:e,S=(t,e,n=!1)=>{if(!t)return[];const r=(u,c)=>e(u)-e(c),i=(u,c)=>e(c)-e(u);return t.slice().sort(n===!0?i:r)},J=(t,e,n="asc")=>{if(!t)return[];const r=(u,c)=>`${e(u)}`.localeCompare(e(c)),i=(u,c)=>`${e(c)}`.localeCompare(e(u));return t.slice().sort(n==="desc"?i:r)},W=(t,e)=>t?t.reduce((n,r)=>{const i=e(r);return n[i]=(n[i]??0)+1,n},{}):{},X=(t,e,n)=>{if(!t)return[];if(!e)return[...t];for(let r=0;rr)=>t.reduce((r,i)=>(r[e(i)]=n(i),r),{}),G=(t,e,n)=>t?t.reduce((r,i,u)=>(n(i,u)&&r.push(e(i,u)),r),[]):[],H=(t,e)=>{const n=e||(r=>r);return O(t,(r,i)=>n(r)>n(i)?r:i)},Q=(t,e)=>{const n=e||(r=>r);return O(t,(r,i)=>n(r){const n=Math.ceil(t.length/e);return new Array(n).fill(null).map((r,i)=>t.slice(i*e,i*e+e))},x=(t,e)=>{const n=t.reduce((r,i)=>{const u=e?e(i):i;return r[u]||(r[u]=i),r},{});return Object.values(n)};function*A(t,e,n=i=>i,r=1){const i=y(n)?n:()=>n,u=e?t:0,c=e??t;for(let o=u;o<=c&&(yield i(o),!(o+r>c));o+=r);}const C=(t,e,n,r)=>Array.from(A(t,e,n,r)),tt=t=>t.reduce((e,n)=>(e.push(...n),e),[]),et=(t,e,n)=>{if(!t||!e)return!1;const r=n??(u=>u),i=e.reduce((u,c)=>(u[r(c)]=!0,u),{});return t.some(u=>i[r(u)])},T=(t,e)=>t?t.reduce((n,r)=>{const[i,u]=n;return e(r)?[[...i,r],u]:[i,[...u,r]]},[[],[]]):[[],[]],nt=(t,e,n)=>!e&&!t?[]:e?t?n?t.reduce((r,i)=>{const u=e.find(c=>n(i)===n(c));return u?r.push(u):r.push(i),r},[]):t:[]:t,rt=(t,e,n)=>{if(!t&&!e)return[];if(!e)return[...t];if(!t)return[e];for(let r=0;r{if(!t&&!e)return[];if(!t)return[e];if(!e)return[...t];const i=n?(o,l)=>n(o,l)===n(e,l):o=>o===e;return t.find(i)?t.filter((o,l)=>!i(o,l)):(r?.strategy??"append")==="append"?[...t,e]:[e,...t]},st=t=>t?.filter(e=>!!e)??[],B=(t,e,n)=>{let r=n;for(let i=1;i<=t;i++)r=e(r,i);return r},ut=(t,e,n=r=>r)=>{if(!t?.length&&!e?.length)return[];if(t?.length===void 0)return[...e];if(!e?.length)return[...t];const r=e.reduce((i,u)=>(i[n(u)]=!0,i),{});return t.filter(i=>!r[n(i)])};function ct(t,e){if(t.length===0)return t;const n=e%t.length;return n===0?t:[...t.slice(-n,t.length),...t.slice(0,-n)]}const ot=async(t,e,n)=>{const r=n!==void 0;if(!r&&t?.length<1)throw new Error("Cannot reduce empty array with no init value");const i=r?t:t.slice(1);let u=r?n:t[0];for(const c of i)u=await e(u,c);return u},ft=async(t,e)=>{if(!t)return[];let n=[],r=0;for(const i of t){const u=await e(i,r++);n.push(u)}return n},lt=async t=>{const e=[],n=(u,c)=>e.push({fn:u,rethrow:c?.rethrow??!1}),[r,i]=await m(t)(n);for(const{fn:u,rethrow:c}of e){const[o]=await m(u)(r);if(c)throw o}if(r)throw r;return i};class at extends Error{constructor(e=[]){super();const n=e.find(r=>r.name)?.name??"";this.name=`AggregateError(${n}...)`,this.message=`AggregateError with ${e.length} errors`,this.stack=e.find(r=>r.stack)?.stack??this.stack,this.errors=e}}const dt=async(t,e,n)=>{const r=e.map((a,p)=>({index:p,item:a})),i=async a=>{const p=[];for(;;){const f=r.pop();if(!f)return a(p);const[d,g]=await m(n)(f.item);p.push({error:d,result:g,index:f.index})}},u=C(1,t).map(()=>new Promise(i)),c=await Promise.all(u),[o,l]=T(S(c.flat(),a=>a.index),a=>!!a.error);if(o.length>0)throw new at(o.map(a=>a.error));return l.map(a=>a.result)},gt=async(t,e)=>{const n=t?.times??3,r=t?.delay,i=t?.backoff??null;for(const u of A(1,n)){const[c,o]=await m(e)(l=>{throw{_exited:l}});if(!c)return o;if(c._exited)throw c._exited;if(u===n)throw c;r&&await E(r),i&&await E(i(u))}},E=t=>new Promise(e=>setTimeout(e,t)),m=t=>async(...e)=>{try{return[void 0,await t(...e)]}catch(n){return[n,void 0]}},ht=(...t)=>(...e)=>t.slice(1).reduce((n,r)=>r(n),t[0](...e)),mt=(...t)=>t.reverse().reduce((e,n)=>n(e)),wt=(t,...e)=>(...n)=>t(...e,...n),pt=(t,e)=>n=>t({...e,...n}),yt=t=>new Proxy({},{get:(e,n)=>t(n)}),bt=(t,e,n,r)=>function(...u){const c=n?n(...u):JSON.stringify({args:u}),o=t[c];if(o!==void 0&&(!o.exp||o.exp>new Date().getTime()))return o.value;const l=e(...u);return t[c]={exp:r?new Date().getTime()+r:null,value:l},l},kt=(t,e={})=>bt({},t,e.key??null,e.ttl??null),Ot=({delay:t},e)=>{let n,r=!0;const i=(...u)=>{r?(clearTimeout(n),n=setTimeout(()=>{r&&e(...u)},t)):e(...u)};return i.cancel=()=>{r=!1},i.flush=(...u)=>e(...u),i},At=({interval:t},e)=>{let n=!0;return(...i)=>{n&&(e(...i),n=!1,setTimeout(()=>{n=!0},t))}},Ct=(t,e)=>{const n=()=>{};return new Proxy(Object.assign(n,t),{get:(r,i)=>r[i],set:(r,i,u)=>(r[i]=u,!0),apply:(r,i,u)=>e(Object.assign({},r))(...u)})},Et=(t,e)=>{const n=e===void 0?0:e;if(t==null)return n;const r=parseFloat(t);return isNaN(r)?n:r},$t=(t,e)=>{const n=e===void 0?0:e;if(t==null)return n;const r=parseInt(t);return isNaN(r)?n:r},Nt=(t,e=n=>n===void 0)=>t?Object.keys(t).reduce((r,i)=>(e(t[i])||(r[i]=t[i]),r),{}):{},$=(t,e)=>Object.keys(t).reduce((r,i)=>(r[e(i,t[i])]=t[i],r),{}),_t=(t,e)=>Object.keys(t).reduce((r,i)=>(r[i]=e(t[i],i),r),{}),jt=(t,e)=>t?Object.entries(t).reduce((n,[r,i])=>{const[u,c]=e(r,i);return n[u]=c,n},{}):{},zt=t=>t?Object.keys(t).reduce((n,r)=>(n[t[r]]=r,n),{}):{},Pt=t=>$(t,e=>e.toLowerCase()),St=t=>$(t,e=>e.toUpperCase()),Tt=t=>{if(j(t))return t;if(typeof t=="function")return t.bind({});const e=new t.constructor;return Object.getOwnPropertyNames(t).forEach(n=>{e[n]=t[n]}),e},Bt=(t,e)=>{if(!t)return[];const n=Object.entries(t);return n.length===0?[]:n.reduce((r,i)=>(r.push(e(i[0],i[1])),r),[])},Lt=(t,e)=>t?e.reduce((n,r)=>(t.hasOwnProperty(r)&&(n[r]=t[r]),n),{}):{},Mt=(t,e)=>t?!e||e.length===0?t:e.reduce((n,r)=>(delete n[r],n),{...t}):{},Dt=(t,e,n=null)=>{const r=e.split(/[\.\[\]]/g);let i=t;for(const u of r){if(i===null||i===void 0)return n;u.trim()!==""&&(i=i[u])}return i===void 0?n:i},L=(t,e)=>!t&&!e?{}:t?e?Object.entries(t).reduce((n,[r,i])=>({...n,[r]:(()=>k(i)?L(i,e[r]):e[r])()}),{}):t:e,Ft=t=>{if(!t)return[];const e=(n,r)=>k(n)?Object.entries(n).flatMap(([i,u])=>e(u,[...r,i])):b(n)?n.flatMap((i,u)=>e(i,[...r,`${u}`])):[r.join(".")];return e(t,[])},N=(t,e)=>Math.floor(Math.random()*(e-t+1)+t),Rt=t=>{const e=t.length;if(e===0)return null;const n=N(0,e-1);return t[n]},Zt=t=>t.map(e=>({rand:Math.random(),value:e})).sort((e,n)=>e.rand-n.rand).map(e=>e.value),qt=(t,e="")=>{const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"+e;return B(t,r=>r+n.charAt(N(0,n.length-1)),"")},It=(t,e=n=>`${n}`)=>{const{indexesByKey:n,itemsByIndex:r}=t.reduce((f,d,g)=>({indexesByKey:{...f.indexesByKey,[e(d)]:g},itemsByIndex:{...f.itemsByIndex,[g]:d}}),{indexesByKey:{},itemsByIndex:{}}),i=(f,d)=>n[e(f)]n[e(f)]>n[e(d)]?f:d,c=()=>r[0],o=()=>r[t.length-1],l=f=>r[n[e(f)]+1]??c(),a=f=>r[n[e(f)]-1]??o();return{min:i,max:u,first:c,last:o,next:l,previous:a,spin:(f,d)=>{if(d===0)return f;const g=Math.abs(d),Gt=g>t.length?g%t.length:g;return C(0,Gt-1).reduce(d>0?l:a,f)}}},w=t=>{if(!t||t.length===0)return"";const e=t.toLowerCase();return e.substring(0,1).toUpperCase()+e.substring(1,e.length)},Ut=t=>{const e=t?.replace(/([A-Z])+/g,w)?.split(/(?=[A-Z])|[\.\-\s_]/).map(n=>n.toLowerCase())??[];return e.length===0?"":e.length===1?e[0]:e.reduce((n,r)=>`${n}${r.charAt(0).toUpperCase()}${r.slice(1)}`)},Kt=t=>{const e=t?.replace(/([A-Z])+/g,w).split(/(?=[A-Z])|[\.\-\s_]/).map(n=>n.toLowerCase())??[];return e.length===0?"":e.length===1?e[0]:e.reduce((n,r)=>`${n}_${r.toLowerCase()}`)},vt=t=>{const e=t?.replace(/([A-Z])+/g,w)?.split(/(?=[A-Z])|[\.\-\s_]/).map(n=>n.toLowerCase())??[];return e.length===0?"":e.length===1?e[0]:e.reduce((n,r)=>`${n}-${r.toLowerCase()}`)},Jt=t=>{const e=t?.split(/[\.\-\s_]/).map(n=>n.toLowerCase())??[];return e.length===0?"":e.map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("")},Wt=t=>t?t.split(/(?=[A-Z])|[\.\-\s_]/).map(e=>e.trim()).filter(e=>!!e).map(e=>w(e.toLowerCase())).join(" "):"",Xt=(t,e,n=/\{\{(.+?)\}\}/g)=>Array.from(t.matchAll(n)).reduce((r,i)=>r.replace(i[0],e[i[1]]),t),Yt=(t,e=" ")=>{if(!t)return"";const n=new RegExp(`^[${e}]+|[${e}]+$`,"g");return t.replace(n,"")};return s.alphabetical=J,s.assign=L,s.boil=O,s.callable=Ct,s.camel=Ut,s.capitalize=w,s.chain=ht,s.clone=Tt,s.cluster=V,s.compose=mt,s.counting=W,s.dash=vt,s.debounce=Ot,s.defer=lt,s.diff=ut,s.draw=Rt,s.first=K,s.flat=tt,s.fork=T,s.get=Dt,s.group=Z,s.intersects=et,s.invert=zt,s.isArray=b,s.isDate=z,s.isEmpty=R,s.isEqual=P,s.isFloat=F,s.isFunction=y,s.isInt=D,s.isNumber=h,s.isObject=k,s.isPrimitive=j,s.isString=M,s.isSymbol=_,s.iterate=B,s.keys=Ft,s.last=v,s.list=C,s.listify=Bt,s.lowerize=Pt,s.map=ft,s.mapEntries=jt,s.mapKeys=$,s.mapValues=_t,s.max=H,s.memo=kt,s.merge=nt,s.min=Q,s.objectify=Y,s.omit=Mt,s.parallel=dt,s.partial=wt,s.partob=pt,s.pascal=Jt,s.pick=Lt,s.proxied=yt,s.random=N,s.range=A,s.reduce=ot,s.replace=X,s.replaceOrAppend=rt,s.retry=gt,s.select=G,s.series=It,s.shake=Nt,s.shift=ct,s.shuffle=Zt,s.sift=st,s.sleep=E,s.snake=Kt,s.sort=S,s.sum=U,s.template=Xt,s.throttle=At,s.title=Wt,s.toFloat=Et,s.toInt=$t,s.toggle=it,s.trim=Yt,s.try=m,s.tryit=m,s.uid=qt,s.unique=x,s.upperize=St,s.zip=q,s.zipToObject=I,s}({}); +var radash=function(s){"use strict";const _=t=>!!t&&t.constructor===Symbol,b=t=>!!t&&t.constructor===Array,k=t=>!!t&&t.constructor===Object,j=t=>t==null||typeof t!="object"&&typeof t!="function",p=t=>!!(t&&t.constructor&&t.call&&t.apply),R=t=>typeof t=="string"||t instanceof String,Z=t=>h(t)&&t%1===0,q=t=>h(t)&&t%1!==0,h=t=>{try{return Number(t)===t}catch{return!1}},z=t=>Object.prototype.toString.call(t)==="[object Date]",I=t=>{if(t===!0||t===!1||t==null)return!0;if(h(t))return t===0;if(z(t))return isNaN(t.getTime());if(p(t)||_(t))return!1;const e=t.length;if(h(e))return e===0;const n=t.size;return h(n)?n===0:Object.keys(t).length===0},P=(t,e)=>{if(Object.is(t,e))return!0;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(t instanceof RegExp&&e instanceof RegExp)return t.toString()===e.toString();if(typeof t!="object"||t===null||typeof e!="object"||e===null)return!1;const n=Reflect.ownKeys(t),r=Reflect.ownKeys(e);if(n.length!==r.length)return!1;for(let i=0;it.reduce((n,r)=>{const i=e(r);return n[i]||(n[i]=[]),n[i].push(r),n},{});function K(...t){return!t||!t.length?[]:new Array(Math.max(...t.map(({length:e})=>e))).fill([]).map((e,n)=>t.map(r=>r[n]))}function J(t,e){if(!t||!t.length)return{};const n=p(e)?e:b(e)?(r,i)=>e[i]:(r,i)=>e;return t.reduce((r,i,u)=>(r[i]=n(i,u),r),{})}const O=(t,e)=>!t||(t.length??0)===0?null:t.reduce(e),W=(t,e)=>(t||[]).reduce((n,r)=>n+(e?e(r):r),0),X=(t,e=void 0)=>t?.length>0?t[0]:e,Y=(t,e=void 0)=>t?.length>0?t[t.length-1]:e,S=(t,e,n=!1)=>{if(!t)return[];const r=(u,c)=>e(u)-e(c),i=(u,c)=>e(c)-e(u);return t.slice().sort(n===!0?i:r)},G=(t,e,n="asc")=>{if(!t)return[];const r=(u,c)=>`${e(u)}`.localeCompare(e(c)),i=(u,c)=>`${e(c)}`.localeCompare(e(u));return t.slice().sort(n==="desc"?i:r)},H=(t,e)=>t?t.reduce((n,r)=>{const i=e(r);return n[i]=(n[i]??0)+1,n},{}):{},Q=(t,e,n)=>{if(!t)return[];if(!e)return[...t];for(let r=0;rr)=>t.reduce((r,i)=>(r[e(i)]=n(i),r),{}),V=(t,e,n)=>t?t.reduce((r,i,u)=>(n(i,u)&&r.push(e(i,u)),r),[]):[],v=(t,e)=>{const n=e||(r=>r);return O(t,(r,i)=>n(r)>n(i)?r:i)},x=(t,e)=>{const n=e||(r=>r);return O(t,(r,i)=>n(r){const n=Math.ceil(t.length/e);return new Array(n).fill(null).map((r,i)=>t.slice(i*e,i*e+e))},et=(t,e)=>{const n=t.reduce((r,i)=>{const u=e?e(i):i;return r[u]||(r[u]=i),r},{});return Object.values(n)};function*A(t,e,n=i=>i,r=1){const i=p(n)?n:()=>n,u=e?t:0,c=e??t;for(let o=u;o<=c&&(yield i(o),!(o+r>c));o+=r);}const C=(t,e,n,r)=>Array.from(A(t,e,n,r)),nt=t=>t.reduce((e,n)=>(e.push(...n),e),[]),rt=(t,e,n)=>{if(!t||!e)return!1;const r=n??(u=>u),i=e.reduce((u,c)=>(u[r(c)]=!0,u),{});return t.some(u=>i[r(u)])},B=(t,e)=>t?t.reduce((n,r)=>{const[i,u]=n;return e(r)?[[...i,r],u]:[i,[...u,r]]},[[],[]]):[[],[]],it=(t,e,n)=>!e&&!t?[]:e?t?n?t.reduce((r,i)=>{const u=e.find(c=>n(i)===n(c));return u?r.push(u):r.push(i),r},[]):t:[]:t,st=(t,e,n)=>{if(!t&&!e)return[];if(!e)return[...t];if(!t)return[e];for(let r=0;r{if(!t&&!e)return[];if(!t)return[e];if(!e)return[...t];const i=n?(o,l)=>n(o,l)===n(e,l):o=>o===e;return t.find(i)?t.filter((o,l)=>!i(o,l)):(r?.strategy??"append")==="append"?[...t,e]:[e,...t]},ct=t=>t?.filter(e=>!!e)??[],L=(t,e,n)=>{let r=n;for(let i=1;i<=t;i++)r=e(r,i);return r},ot=(t,e,n=r=>r)=>{if(!t?.length&&!e?.length)return[];if(t?.length===void 0)return[...e];if(!e?.length)return[...t];const r=e.reduce((i,u)=>(i[n(u)]=!0,i),{});return t.filter(i=>!r[n(i)])};function ft(t,e){if(t.length===0)return t;const n=e%t.length;return n===0?t:[...t.slice(-n,t.length),...t.slice(0,-n)]}const lt=async(t,e,n)=>{const r=n!==void 0;if(!r&&t?.length<1)throw new Error("Cannot reduce empty array with no init value");const i=r?t:t.slice(1);let u=r?n:t[0];for(const c of i)u=await e(u,c);return u},at=async(t,e)=>{if(!t)return[];let n=[],r=0;for(const i of t){const u=await e(i,r++);n.push(u)}return n},dt=async t=>{const e=[],n=(u,c)=>e.push({fn:u,rethrow:c?.rethrow??!1}),[r,i]=await m(t)(n);for(const{fn:u,rethrow:c}of e){const[o]=await m(u)(r);if(c)throw o}if(r)throw r;return i};class gt extends Error{constructor(e=[]){super();const n=e.find(r=>r.name)?.name??"";this.name=`AggregateError(${n}...)`,this.message=`AggregateError with ${e.length} errors`,this.stack=e.find(r=>r.stack)?.stack??this.stack,this.errors=e}}const ht=async(t,e,n)=>{const r=e.map((a,y)=>({index:y,item:a})),i=async a=>{const y=[];for(;;){const f=r.pop();if(!f)return a(y);const[d,g]=await m(n)(f.item);y.push({error:d,result:g,index:f.index})}},u=C(1,t).map(()=>new Promise(i)),c=await Promise.all(u),[o,l]=B(S(c.flat(),a=>a.index),a=>!!a.error);if(o.length>0)throw new gt(o.map(a=>a.error));return l.map(a=>a.result)},mt=async(t,e)=>{const n=t?.times??3,r=t?.delay,i=t?.backoff??null;for(const u of A(1,n)){const[c,o]=await m(e)(l=>{throw{_exited:l}});if(!c)return o;if(c._exited)throw c._exited;if(u===n)throw c;r&&await E(r),i&&await E(i(u))}},E=t=>new Promise(e=>setTimeout(e,t)),m=t=>async(...e)=>{try{return[void 0,await t(...e)]}catch(n){return[n,void 0]}},wt=(...t)=>(...e)=>t.slice(1).reduce((n,r)=>r(n),t[0](...e)),yt=(...t)=>t.reverse().reduce((e,n)=>n(e)),pt=(t,...e)=>(...n)=>t(...e,...n),bt=(t,e)=>n=>t({...e,...n}),kt=t=>new Proxy({},{get:(e,n)=>t(n)}),Ot=(t,e,n,r)=>function(...u){const c=n?n(...u):JSON.stringify({args:u}),o=t[c];if(o!==void 0&&(!o.exp||o.exp>new Date().getTime()))return o.value;const l=e(...u);return t[c]={exp:r?new Date().getTime()+r:null,value:l},l},At=(t,e={})=>Ot({},t,e.key??null,e.ttl??null),Ct=({delay:t},e)=>{let n,r=!0;const i=(...u)=>{r?(clearTimeout(n),n=setTimeout(()=>{r&&e(...u)},t)):e(...u)};return i.cancel=()=>{r=!1},i.flush=(...u)=>e(...u),i},Et=({interval:t},e)=>{let n=!0;return(...i)=>{n&&(e(...i),n=!1,setTimeout(()=>{n=!0},t))}},$t=(t,e)=>{const n=()=>{};return new Proxy(Object.assign(n,t),{get:(r,i)=>r[i],set:(r,i,u)=>(r[i]=u,!0),apply:(r,i,u)=>e(Object.assign({},r))(...u)})},Nt=(t,e)=>{const n=e===void 0?0:e;if(t==null)return n;const r=parseFloat(t);return isNaN(r)?n:r},_t=(t,e)=>{const n=e===void 0?0:e;if(t==null)return n;const r=parseInt(t);return isNaN(r)?n:r},jt=(t,e=n=>n===void 0)=>t?Object.keys(t).reduce((r,i)=>(e(t[i])||(r[i]=t[i]),r),{}):{},$=(t,e)=>Object.keys(t).reduce((r,i)=>(r[e(i,t[i])]=t[i],r),{}),zt=(t,e)=>Object.keys(t).reduce((r,i)=>(r[i]=e(t[i],i),r),{}),Pt=(t,e)=>t?Object.entries(t).reduce((n,[r,i])=>{const[u,c]=e(r,i);return n[u]=c,n},{}):{},St=t=>t?Object.keys(t).reduce((n,r)=>(n[t[r]]=r,n),{}):{},Tt=t=>$(t,e=>e.toLowerCase()),Bt=t=>$(t,e=>e.toUpperCase()),Lt=t=>{if(j(t))return t;if(typeof t=="function")return t.bind({});const e=new t.constructor;return Object.getOwnPropertyNames(t).forEach(n=>{e[n]=t[n]}),e},Mt=(t,e)=>{if(!t)return[];const n=Object.entries(t);return n.length===0?[]:n.reduce((r,i)=>(r.push(e(i[0],i[1])),r),[])},Dt=(t,e)=>t?e.reduce((n,r)=>(t.hasOwnProperty(r)&&(n[r]=t[r]),n),{}):{},Ft=(t,e)=>t?!e||e.length===0?t:e.reduce((n,r)=>(delete n[r],n),{...t}):{},M=(t,e,n=null)=>{const r=e.split(/[\.\[\]]/g);let i=t;for(const u of r){if(i===null||i===void 0)return n;u.trim()!==""&&(i=i[u])}return i===void 0?n:i},D=(t,e)=>!t&&!e?{}:t?e?Object.entries(t).reduce((n,[r,i])=>({...n,[r]:(()=>k(i)?D(i,e[r]):e[r])()}),{}):t:e,F=t=>{if(!t)return[];const e=(n,r)=>k(n)?Object.entries(n).flatMap(([i,u])=>e(u,[...r,i])):b(n)?n.flatMap((i,u)=>e(i,[...r,`${u}`])):[r.join(".")];return e(t,[])},Rt=t=>t?T(F(t),e=>e,e=>M(t,e)):{},N=(t,e)=>Math.floor(Math.random()*(e-t+1)+t),Zt=t=>{const e=t.length;if(e===0)return null;const n=N(0,e-1);return t[n]},qt=t=>t.map(e=>({rand:Math.random(),value:e})).sort((e,n)=>e.rand-n.rand).map(e=>e.value),It=(t,e="")=>{const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"+e;return L(t,r=>r+n.charAt(N(0,n.length-1)),"")},Ut=(t,e=n=>`${n}`)=>{const{indexesByKey:n,itemsByIndex:r}=t.reduce((f,d,g)=>({indexesByKey:{...f.indexesByKey,[e(d)]:g},itemsByIndex:{...f.itemsByIndex,[g]:d}}),{indexesByKey:{},itemsByIndex:{}}),i=(f,d)=>n[e(f)]n[e(f)]>n[e(d)]?f:d,c=()=>r[0],o=()=>r[t.length-1],l=f=>r[n[e(f)]+1]??c(),a=f=>r[n[e(f)]-1]??o();return{min:i,max:u,first:c,last:o,next:l,previous:a,spin:(f,d)=>{if(d===0)return f;const g=Math.abs(d),Qt=g>t.length?g%t.length:g;return C(0,Qt-1).reduce(d>0?l:a,f)}}},w=t=>{if(!t||t.length===0)return"";const e=t.toLowerCase();return e.substring(0,1).toUpperCase()+e.substring(1,e.length)},Kt=t=>{const e=t?.replace(/([A-Z])+/g,w)?.split(/(?=[A-Z])|[\.\-\s_]/).map(n=>n.toLowerCase())??[];return e.length===0?"":e.length===1?e[0]:e.reduce((n,r)=>`${n}${r.charAt(0).toUpperCase()}${r.slice(1)}`)},Jt=t=>{const e=t?.replace(/([A-Z])+/g,w).split(/(?=[A-Z])|[\.\-\s_]/).map(n=>n.toLowerCase())??[];return e.length===0?"":e.length===1?e[0]:e.reduce((n,r)=>`${n}_${r.toLowerCase()}`)},Wt=t=>{const e=t?.replace(/([A-Z])+/g,w)?.split(/(?=[A-Z])|[\.\-\s_]/).map(n=>n.toLowerCase())??[];return e.length===0?"":e.length===1?e[0]:e.reduce((n,r)=>`${n}-${r.toLowerCase()}`)},Xt=t=>{const e=t?.split(/[\.\-\s_]/).map(n=>n.toLowerCase())??[];return e.length===0?"":e.map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("")},Yt=t=>t?t.split(/(?=[A-Z])|[\.\-\s_]/).map(e=>e.trim()).filter(e=>!!e).map(e=>w(e.toLowerCase())).join(" "):"",Gt=(t,e,n=/\{\{(.+?)\}\}/g)=>Array.from(t.matchAll(n)).reduce((r,i)=>r.replace(i[0],e[i[1]]),t),Ht=(t,e=" ")=>{if(!t)return"";const n=new RegExp(`^[${e}]+|[${e}]+$`,"g");return t.replace(n,"")};return s.alphabetical=G,s.assign=D,s.boil=O,s.callable=$t,s.camel=Kt,s.capitalize=w,s.chain=wt,s.clone=Lt,s.cluster=tt,s.compose=yt,s.counting=H,s.crush=Rt,s.dash=Wt,s.debounce=Ct,s.defer=dt,s.diff=ot,s.draw=Zt,s.first=X,s.flat=nt,s.fork=B,s.get=M,s.group=U,s.intersects=rt,s.invert=St,s.isArray=b,s.isDate=z,s.isEmpty=I,s.isEqual=P,s.isFloat=q,s.isFunction=p,s.isInt=Z,s.isNumber=h,s.isObject=k,s.isPrimitive=j,s.isString=R,s.isSymbol=_,s.iterate=L,s.keys=F,s.last=Y,s.list=C,s.listify=Mt,s.lowerize=Tt,s.map=at,s.mapEntries=Pt,s.mapKeys=$,s.mapValues=zt,s.max=v,s.memo=At,s.merge=it,s.min=x,s.objectify=T,s.omit=Ft,s.parallel=ht,s.partial=pt,s.partob=bt,s.pascal=Xt,s.pick=Dt,s.proxied=kt,s.random=N,s.range=A,s.reduce=lt,s.replace=Q,s.replaceOrAppend=st,s.retry=mt,s.select=V,s.series=Ut,s.shake=jt,s.shift=ft,s.shuffle=qt,s.sift=ct,s.sleep=E,s.snake=Jt,s.sort=S,s.sum=W,s.template=Gt,s.throttle=Et,s.title=Yt,s.toFloat=Nt,s.toInt=_t,s.toggle=ut,s.trim=Ht,s.try=m,s.tryit=m,s.uid=It,s.unique=et,s.upperize=Bt,s.zip=K,s.zipToObject=J,s}({}); diff --git a/docs/object/crush.mdx b/docs/object/crush.mdx new file mode 100644 index 00000000..aebcdcac --- /dev/null +++ b/docs/object/crush.mdx @@ -0,0 +1,38 @@ +--- +title: crush +description: Flattens a deep object to a single dimension +group: Object +--- + +## Basic usage + +Flattens a deep object to a single dimension. The deep keys will be converted to a dot notation in the new object. + +```ts +import { crush } from 'radash' + +const ra = { + name: 'ra', + power: 100, + friend: { + name: 'loki', + power: 80 + }, + enemies: [ + { + name: 'hathor', + power: 12 + } + ] +} + +crush(ra) +// { +// name: 'ra', +// power: 100, +// 'friend.name': 'loki', +// 'friend.power': 80, +// 'enemies.0.name': 'hathor', +// 'enemies.0.power': 12 +// } +``` diff --git a/docs/object/keys.mdx b/docs/object/keys.mdx index 857d9c00..863e8b88 100644 --- a/docs/object/keys.mdx +++ b/docs/object/keys.mdx @@ -56,3 +56,5 @@ objectify( // 'enemies.0.power': 12 // } ``` + +_As of v10.5.0+ you can get this behavior via the crush function_ diff --git a/package.json b/package.json index cd8ebb61..ba670cc0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "radash", - "version": "10.4.0", + "version": "10.5.0", "description": "Functional utility library - modern, simple, typed, powerful", "main": "dist/cjs/index.cjs", "module": "dist/esm/index.mjs", diff --git a/src/index.ts b/src/index.ts index f8e182c5..d33bbfb1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -55,6 +55,7 @@ export { toFloat, toInt } from './number' export { assign, clone, + crush, get, invert, keys, diff --git a/src/object.ts b/src/object.ts index 6632799c..6c461d1c 100644 --- a/src/object.ts +++ b/src/object.ts @@ -1,3 +1,4 @@ +import { objectify } from './array' import { isArray, isObject, isPrimitive } from './typed' type LowercasedKeys> = { @@ -269,3 +270,20 @@ export const keys = (value: TValue): string[] => { } return getKeys(value, []) } + +/** + * Flattens a deep object to a single demension, converting + * the keys to dot notation. + * + * @example + * crush({ name: 'ra', children: [{ name: 'hathor' }] }) + * // { name: 'ra', 'children.0.name': 'hathor' } + */ +export const crush = (value: TValue): object => { + if (!value) return {} + return objectify( + keys(value), + k => k, + k => get(value, k) + ) +} diff --git a/src/tests/object.test.ts b/src/tests/object.test.ts index 8d11378c..d9599f11 100644 --- a/src/tests/object.test.ts +++ b/src/tests/object.test.ts @@ -415,4 +415,36 @@ describe('object module', () => { ]) }) }) + + describe('crush function', () => { + test('handles bad input', () => { + assert.deepEqual(_.crush({}), {}) + assert.deepEqual(_.crush(null as any), {}) + assert.deepEqual(_.crush(undefined as any), {}) + }) + test('returns correctly crushed object', () => { + const ra = { + name: 'ra', + power: 100, + friend: { + name: 'loki', + power: 80 + }, + enemies: [ + { + name: 'hathor', + power: 12 + } + ] + } + assert.deepEqual(_.crush(ra), { + name: 'ra', + power: 100, + 'friend.name': 'loki', + 'friend.power': 80, + 'enemies.0.name': 'hathor', + 'enemies.0.power': 12 + }) + }) + }) })