diff --git a/cdn/radash.esm.js b/cdn/radash.esm.js index a0a63559..379dd0a0 100644 --- a/cdn/radash.esm.js +++ b/cdn/radash.esm.js @@ -695,6 +695,14 @@ const pick = (obj, keys2) => { return acc; }, {}); }; +const pickBy = (obj, predicate = () => true) => { + if (!obj) + return {}; + return pick( + obj, + Object.keys(obj).filter((key) => predicate(obj[key])) + ); +}; const omit = (obj, keys2) => { if (!obj) return {}; @@ -937,4 +945,4 @@ const trim = (str, charsToTrim = " ") => { return str.replace(regex, ""); }; -export { all, alphabetical, assign, boil, callable, camel, capitalize, chain, clone, cluster, compose, construct, counting, crush, dash, debounce, defer, diff, draw, first, flat, fork, get, group, guard, inRange, intersects, invert, isArray, isDate, isEmpty, isEqual, isFloat, isFunction, isInt, isNumber, isObject, isPrimitive, isPromise, 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, set, 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 { all, alphabetical, assign, boil, callable, camel, capitalize, chain, clone, cluster, compose, construct, counting, crush, dash, debounce, defer, diff, draw, first, flat, fork, get, group, guard, inRange, intersects, invert, isArray, isDate, isEmpty, isEqual, isFloat, isFunction, isInt, isNumber, isObject, isPrimitive, isPromise, isString, isSymbol, iterate, keys, last, list, listify, lowerize, map, mapEntries, mapKeys, mapValues, max, memo, merge, min, objectify, omit, parallel, partial, partob, pascal, pick, pickBy, proxied, random, range, reduce, replace, replaceOrAppend, retry, select, series, set, 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 ca7ebea6..c5fcd05c 100644 --- a/cdn/radash.js +++ b/cdn/radash.js @@ -698,6 +698,14 @@ var radash = (function (exports) { return acc; }, {}); }; + const pickBy = (obj, predicate = () => true) => { + if (!obj) + return {}; + return pick( + obj, + Object.keys(obj).filter((key) => predicate(obj[key])) + ); + }; const omit = (obj, keys2) => { if (!obj) return {}; @@ -1002,6 +1010,7 @@ var radash = (function (exports) { exports.partob = partob; exports.pascal = pascal; exports.pick = pick; + exports.pickBy = pickBy; exports.proxied = proxied; exports.random = random; exports.range = range; diff --git a/cdn/radash.min.js b/cdn/radash.min.js index f9363f50..7a9eac38 100644 --- a/cdn/radash.min.js +++ b/cdn/radash.min.js @@ -1 +1 @@ -var radash=function(i){"use strict";const E=e=>!!e&&e.constructor===Symbol,w=Array.isArray,k=e=>!!e&&e.constructor===Object,N=e=>e==null||typeof e!="object"&&typeof e!="function",y=e=>!!(e&&e.constructor&&e.call&&e.apply),K=e=>typeof e=="string"||e instanceof String,W=e=>h(e)&&e%1===0,J=e=>h(e)&&e%1!==0,h=e=>{try{return Number(e)===e}catch{return!1}},T=e=>Object.prototype.toString.call(e)==="[object Date]",S=e=>!(!e||!e.then||!y(e.then)),X=e=>{if(e===!0||e===!1||e==null)return!0;if(h(e))return e===0;if(T(e))return isNaN(e.getTime());if(y(e)||E(e))return!1;const t=e.length;if(h(t))return t===0;const n=e.size;return h(n)?n===0:Object.keys(e).length===0},j=(e,t)=>{if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e instanceof RegExp&&t instanceof RegExp)return e.toString()===t.toString();if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;const n=Reflect.ownKeys(e),r=Reflect.ownKeys(t);if(n.length!==r.length)return!1;for(let s=0;se.reduce((n,r)=>{const s=t(r);return n[s]||(n[s]=[]),n[s].push(r),n},{});function H(...e){return!e||!e.length?[]:new Array(Math.max(...e.map(({length:t})=>t))).fill([]).map((t,n)=>e.map(r=>r[n]))}function Q(e,t){if(!e||!e.length)return{};const n=y(t)?t:w(t)?(r,s)=>t[s]:(r,s)=>t;return e.reduce((r,s,u)=>(r[s]=n(s,u),r),{})}const O=(e,t)=>!e||(e.length??0)===0?null:e.reduce(t);function V(e,t){return(e||[]).reduce((n,r)=>n+(t?t(r):r),0)}const G=(e,t=void 0)=>e?.length>0?e[0]:t,x=(e,t=void 0)=>e?.length>0?e[e.length-1]:t,z=(e,t,n=!1)=>{if(!e)return[];const r=(u,c)=>t(u)-t(c),s=(u,c)=>t(c)-t(u);return e.slice().sort(n===!0?s:r)},ee=(e,t,n="asc")=>{if(!e)return[];const r=(u,c)=>`${t(u)}`.localeCompare(t(c)),s=(u,c)=>`${t(c)}`.localeCompare(t(u));return e.slice().sort(n==="desc"?s:r)},te=(e,t)=>e?e.reduce((n,r)=>{const s=t(r);return n[s]=(n[s]??0)+1,n},{}):{},ne=(e,t,n)=>{if(!e)return[];if(t===void 0)return[...e];for(let r=0;rr)=>e.reduce((r,s)=>(r[t(s)]=n(s),r),{}),re=(e,t,n)=>e?e.reduce((r,s,u)=>(n(s,u)&&r.push(t(s,u)),r),[]):[];function se(e,t){const n=t??(r=>r);return O(e,(r,s)=>n(r)>n(s)?r:s)}function ie(e,t){const n=t??(r=>r);return O(e,(r,s)=>n(r){const n=Math.ceil(e.length/t);return new Array(n).fill(null).map((r,s)=>e.slice(s*t,s*t+t))},ce=(e,t)=>{const n=e.reduce((r,s)=>{const u=t?t(s):s;return r[u]||(r[u]=s),r},{});return Object.values(n)};function*A(e,t,n=s=>s,r=1){const s=y(n)?n:()=>n,u=t?e:0,c=t??e;for(let o=u;o<=c&&(yield s(o),!(o+r>c));o+=r);}const C=(e,t,n,r)=>Array.from(A(e,t,n,r)),oe=e=>e.reduce((t,n)=>(t.push(...n),t),[]),fe=(e,t,n)=>{if(!e||!t)return!1;const r=n??(u=>u),s=t.reduce((u,c)=>(u[r(c)]=!0,u),{});return e.some(u=>s[r(u)])},R=(e,t)=>e?e.reduce((n,r)=>{const[s,u]=n;return t(r)?[[...s,r],u]:[s,[...u,r]]},[[],[]]):[[],[]],le=(e,t,n)=>!t&&!e?[]:t?e?n?e.reduce((r,s)=>{const u=t.find(c=>n(s)===n(c));return u?r.push(u):r.push(s),r},[]):e:[]:e,ae=(e,t,n)=>{if(!e&&!t)return[];if(!t)return[...e];if(!e)return[t];for(let r=0;r{if(!e&&!t)return[];if(!e)return[t];if(!t)return[...e];const s=n?(o,a)=>n(o,a)===n(t,a):o=>o===t;return e.find(s)?e.filter((o,a)=>!s(o,a)):(r?.strategy??"append")==="append"?[...e,t]:[t,...e]},ge=e=>e?.filter(t=>!!t)??[],B=(e,t,n)=>{let r=n;for(let s=1;s<=e;s++)r=t(r,s);return r},he=(e,t,n=r=>r)=>{if(!e?.length&&!t?.length)return[];if(e?.length===void 0)return[...t];if(!t?.length)return[...e];const r=t.reduce((s,u)=>(s[n(u)]=!0,s),{});return e.filter(s=>!r[n(s)])};function me(e,t){if(e.length===0)return e;const n=t%e.length;return n===0?e:[...e.slice(-n,e.length),...e.slice(0,-n)]}const we=async(e,t,n)=>{const r=n!==void 0;if(!r&&e?.length<1)throw new Error("Cannot reduce empty array with no init value");const s=r?e:e.slice(1);let u=r?n:e[0];for(const[c,o]of s.entries())u=await t(u,o,c);return u},ye=async(e,t)=>{if(!e)return[];let n=[],r=0;for(const s of e){const u=await t(s,r++);n.push(u)}return n},pe=async e=>{const t=[],n=(u,c)=>t.push({fn:u,rethrow:c?.rethrow??!1}),[r,s]=await m(e)(n);for(const{fn:u,rethrow:c}of t){const[o]=await m(u)(r);if(o&&c)throw o}if(r)throw r;return s};class L extends Error{constructor(t=[]){super();const n=t.find(r=>r.name)?.name??"";this.name=`AggregateError(${n}...)`,this.message=`AggregateError with ${t.length} errors`,this.stack=t.find(r=>r.stack)?.stack??this.stack,this.errors=t}}const be=async(e,t,n)=>{const r=t.map((d,b)=>({index:b,item:d})),s=async d=>{const b=[];for(;;){const f=r.pop();if(!f)return d(b);const[l,g]=await m(n)(f.item);b.push({error:l,result:g,index:f.index})}},u=C(1,e).map(()=>new Promise(s)),c=await Promise.all(u),[o,a]=R(z(c.flat(),d=>d.index),d=>!!d.error);if(o.length>0)throw new L(o.map(d=>d.error));return a.map(d=>d.result)};async function ke(e){const t=w(e)?e.map(s=>[null,s]):Object.entries(e),n=await Promise.all(t.map(([s,u])=>u.then(c=>({result:c,exc:null,key:s})).catch(c=>({result:null,exc:c,key:s})))),r=n.filter(s=>s.exc);if(r.length>0)throw new L(r.map(s=>s.exc));return w(e)?n.map(s=>s.result):n.reduce((s,u)=>({...s,[u.key]:u.result}),{})}const Oe=async(e,t)=>{const n=e?.times??3,r=e?.delay,s=e?.backoff??null;for(const u of A(1,n)){const[c,o]=await m(t)(a=>{throw{_exited:a}});if(!c)return o;if(c._exited)throw c._exited;if(u===n)throw c;r&&await $(r),s&&await $(s(u))}},$=e=>new Promise(t=>setTimeout(t,e)),m=e=>(...t)=>{try{const n=e(...t);return S(n)?n.then(r=>[void 0,r]).catch(r=>[r,void 0]):[void 0,n]}catch(n){return[n,void 0]}},Ae=(e,t)=>{const n=s=>{if(t&&!t(s))throw s},r=s=>s instanceof Promise;try{const s=e();return r(s)?s.catch(n):s}catch(s){return n(s)}};function Ce(...e){return(...t)=>e.slice(1).reduce((n,r)=>r(n),e[0](...t))}function $e(...e){return e.reverse().reduce((t,n)=>n(t))}const Pe=(e,...t)=>(...n)=>e(...t,...n),_e=(e,t)=>n=>e({...t,...n}),Ee=e=>new Proxy({},{get:(t,n)=>e(n)}),Ne=(e,t,n,r)=>function(...u){const c=n?n(...u):JSON.stringify({args:u}),o=e[c];if(o!==void 0&&(!o.exp||o.exp>new Date().getTime()))return o.value;const a=t(...u);return e[c]={exp:r?new Date().getTime()+r:null,value:a},a},Te=(e,t={})=>Ne({},e,t.key??null,t.ttl??null),Se=({delay:e},t)=>{let n,r=!0;const s=(...u)=>{r?(clearTimeout(n),n=setTimeout(()=>{r&&t(...u),n=void 0},e)):t(...u)};return s.isPending=()=>n!==void 0,s.cancel=()=>{r=!1},s.flush=(...u)=>t(...u),s},je=({interval:e},t)=>{let n=!0,r;const s=(...u)=>{n&&(t(...u),n=!1,r=setTimeout(()=>{n=!0,r=void 0},e))};return s.isThrottled=()=>r!==void 0,s},ze=(e,t)=>{const n=()=>{};return new Proxy(Object.assign(n,e),{get:(r,s)=>r[s],set:(r,s,u)=>(r[s]=u,!0),apply:(r,s,u)=>t(Object.assign({},r))(...u)})};function Me(e,t,n){return typeof e=="number"&&typeof t=="number"&&(typeof n>"u"||typeof n=="number")?(typeof n>"u"&&(n=t,t=0),e>=Math.min(t,n)&&e{const n=t===void 0?0:t;if(e==null)return n;const r=parseFloat(e);return isNaN(r)?n:r},Z=(e,t)=>{const n=t===void 0?0:t;if(e==null)return n;const r=parseInt(e);return isNaN(r)?n:r},Be=(e,t=n=>n===void 0)=>e?Object.keys(e).reduce((r,s)=>(t(e[s])||(r[s]=e[s]),r),{}):{},P=(e,t)=>Object.keys(e).reduce((r,s)=>(r[t(s,e[s])]=e[s],r),{}),Le=(e,t)=>Object.keys(e).reduce((r,s)=>(r[s]=t(e[s],s),r),{}),Ze=(e,t)=>e?Object.entries(e).reduce((n,[r,s])=>{const[u,c]=t(r,s);return n[u]=c,n},{}):{},De=e=>e?Object.keys(e).reduce((n,r)=>(n[e[r]]=r,n),{}):{},Fe=e=>P(e,t=>t.toLowerCase()),qe=e=>P(e,t=>t.toUpperCase()),D=e=>{if(N(e))return e;if(typeof e=="function")return e.bind({});const t=new e.constructor;return Object.getOwnPropertyNames(e).forEach(n=>{t[n]=e[n]}),t},Ie=(e,t)=>{if(!e)return[];const n=Object.entries(e);return n.length===0?[]:n.reduce((r,s)=>(r.push(t(s[0],s[1])),r),[])},ve=(e,t)=>e?t.reduce((n,r)=>(Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]),n),{}):{},Ue=(e,t)=>e?!t||t.length===0?e:t.reduce((n,r)=>(delete n[r],n),{...e}):{},F=(e,t,n)=>{const r=t.split(/[\.\[\]]/g);let s=e;for(const u of r){if(s===null||s===void 0)return n;const c=u.replace(/['"]/g,"");c.trim()!==""&&(s=s[c])}return s===void 0?n:s},q=(e,t,n)=>{if(!e)return{};if(!t||n===void 0)return e;const r=t.split(/[\.\[\]]/g).filter(c=>!!c.trim()),s=c=>{if(r.length>1){const o=r.shift(),a=Z(r[0],null)!==null;c[o]=c[o]===void 0?a?[]:{}:c[o],s(c[o])}else c[r[0]]=n},u=D(e);return s(u),u},I=(e,t)=>!e||!t?e??t??{}:Object.entries({...e,...t}).reduce((n,[r,s])=>({...n,[r]:(()=>k(e[r])?I(e[r],s):s)()}),{}),v=e=>{if(!e)return[];const t=(n,r)=>k(n)?Object.entries(n).flatMap(([s,u])=>t(u,[...r,s])):w(n)?n.flatMap((s,u)=>t(s,[...r,`${u}`])):[r.join(".")];return t(e,[])},Ke=e=>e?M(v(e),t=>t,t=>F(e,t)):{},We=e=>e?Object.keys(e).reduce((t,n)=>q(t,n,e[n]),{}):{},_=(e,t)=>Math.floor(Math.random()*(t-e+1)+e),Je=e=>{const t=e.length;if(t===0)return null;const n=_(0,t-1);return e[n]},Xe=e=>e.map(t=>({rand:Math.random(),value:t})).sort((t,n)=>t.rand-n.rand).map(t=>t.value),Ye=(e,t="")=>{const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"+t;return B(e,r=>r+n.charAt(_(0,n.length-1)),"")},He=(e,t=n=>`${n}`)=>{const{indexesByKey:n,itemsByIndex:r}=e.reduce((f,l,g)=>({indexesByKey:{...f.indexesByKey,[t(l)]:g},itemsByIndex:{...f.itemsByIndex,[g]:l}}),{indexesByKey:{},itemsByIndex:{}}),s=(f,l)=>n[t(f)]n[t(f)]>n[t(l)]?f:l,c=()=>r[0],o=()=>r[e.length-1],a=(f,l)=>r[n[t(f)]+1]??l??c(),d=(f,l)=>r[n[t(f)]-1]??l??o();return{min:s,max:u,first:c,last:o,next:a,previous:d,spin:(f,l)=>{if(l===0)return f;const g=Math.abs(l),rt=g>e.length?g%e.length:g;return C(0,rt-1).reduce(U=>l>0?a(U):d(U),f)}}},p=e=>{if(!e||e.length===0)return"";const t=e.toLowerCase();return t.substring(0,1).toUpperCase()+t.substring(1,t.length)},Qe=e=>{const t=e?.replace(/([A-Z])+/g,p)?.split(/(?=[A-Z])|[\.\-\s_]/).map(n=>n.toLowerCase())??[];return t.length===0?"":t.length===1?t[0]:t.reduce((n,r)=>`${n}${r.charAt(0).toUpperCase()}${r.slice(1)}`)},Ve=(e,t)=>{const n=e?.replace(/([A-Z])+/g,p).split(/(?=[A-Z])|[\.\-\s_]/).map(s=>s.toLowerCase())??[];if(n.length===0)return"";if(n.length===1)return n[0];const r=n.reduce((s,u)=>`${s}_${u.toLowerCase()}`);return t?.splitOnNumber===!1?r:r.replace(/([A-Za-z]{1}[0-9]{1})/,s=>`${s[0]}_${s[1]}`)},Ge=e=>{const t=e?.replace(/([A-Z])+/g,p)?.split(/(?=[A-Z])|[\.\-\s_]/).map(n=>n.toLowerCase())??[];return t.length===0?"":t.length===1?t[0]:t.reduce((n,r)=>`${n}-${r.toLowerCase()}`)},xe=e=>{const t=e?.split(/[\.\-\s_]/).map(n=>n.toLowerCase())??[];return t.length===0?"":t.map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("")},et=e=>e?e.split(/(?=[A-Z])|[\.\-\s_]/).map(t=>t.trim()).filter(t=>!!t).map(t=>p(t.toLowerCase())).join(" "):"",tt=(e,t,n=/\{\{(.+?)\}\}/g)=>Array.from(e.matchAll(n)).reduce((r,s)=>r.replace(s[0],t[s[1]]),e),nt=(e,t=" ")=>{if(!e)return"";const n=t.replace(/[\W]{1}/g,"\\$&"),r=new RegExp(`^[${n}]+|[${n}]+$`,"g");return e.replace(r,"")};return i.all=ke,i.alphabetical=ee,i.assign=I,i.boil=O,i.callable=ze,i.camel=Qe,i.capitalize=p,i.chain=Ce,i.clone=D,i.cluster=ue,i.compose=$e,i.construct=We,i.counting=te,i.crush=Ke,i.dash=Ge,i.debounce=Se,i.defer=pe,i.diff=he,i.draw=Je,i.first=G,i.flat=oe,i.fork=R,i.get=F,i.group=Y,i.guard=Ae,i.inRange=Me,i.intersects=fe,i.invert=De,i.isArray=w,i.isDate=T,i.isEmpty=X,i.isEqual=j,i.isFloat=J,i.isFunction=y,i.isInt=W,i.isNumber=h,i.isObject=k,i.isPrimitive=N,i.isPromise=S,i.isString=K,i.isSymbol=E,i.iterate=B,i.keys=v,i.last=x,i.list=C,i.listify=Ie,i.lowerize=Fe,i.map=ye,i.mapEntries=Ze,i.mapKeys=P,i.mapValues=Le,i.max=se,i.memo=Te,i.merge=le,i.min=ie,i.objectify=M,i.omit=Ue,i.parallel=be,i.partial=Pe,i.partob=_e,i.pascal=xe,i.pick=ve,i.proxied=Ee,i.random=_,i.range=A,i.reduce=we,i.replace=ne,i.replaceOrAppend=ae,i.retry=Oe,i.select=re,i.series=He,i.set=q,i.shake=Be,i.shift=me,i.shuffle=Xe,i.sift=ge,i.sleep=$,i.snake=Ve,i.sort=z,i.sum=V,i.template=tt,i.throttle=je,i.title=et,i.toFloat=Re,i.toInt=Z,i.toggle=de,i.trim=nt,i.try=m,i.tryit=m,i.uid=Ye,i.unique=ce,i.upperize=qe,i.zip=H,i.zipToObject=Q,i}({}); +var radash=function(s){"use strict";const E=e=>!!e&&e.constructor===Symbol,w=Array.isArray,k=e=>!!e&&e.constructor===Object,N=e=>e==null||typeof e!="object"&&typeof e!="function",y=e=>!!(e&&e.constructor&&e.call&&e.apply),W=e=>typeof e=="string"||e instanceof String,J=e=>h(e)&&e%1===0,X=e=>h(e)&&e%1!==0,h=e=>{try{return Number(e)===e}catch{return!1}},T=e=>Object.prototype.toString.call(e)==="[object Date]",S=e=>!(!e||!e.then||!y(e.then)),Y=e=>{if(e===!0||e===!1||e==null)return!0;if(h(e))return e===0;if(T(e))return isNaN(e.getTime());if(y(e)||E(e))return!1;const t=e.length;if(h(t))return t===0;const n=e.size;return h(n)?n===0:Object.keys(e).length===0},z=(e,t)=>{if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e instanceof RegExp&&t instanceof RegExp)return e.toString()===t.toString();if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;const n=Reflect.ownKeys(e),r=Reflect.ownKeys(t);if(n.length!==r.length)return!1;for(let i=0;ie.reduce((n,r)=>{const i=t(r);return n[i]||(n[i]=[]),n[i].push(r),n},{});function Q(...e){return!e||!e.length?[]:new Array(Math.max(...e.map(({length:t})=>t))).fill([]).map((t,n)=>e.map(r=>r[n]))}function V(e,t){if(!e||!e.length)return{};const n=y(t)?t:w(t)?(r,i)=>t[i]:(r,i)=>t;return e.reduce((r,i,u)=>(r[i]=n(i,u),r),{})}const O=(e,t)=>!e||(e.length??0)===0?null:e.reduce(t);function G(e,t){return(e||[]).reduce((n,r)=>n+(t?t(r):r),0)}const x=(e,t=void 0)=>e?.length>0?e[0]:t,ee=(e,t=void 0)=>e?.length>0?e[e.length-1]:t,B=(e,t,n=!1)=>{if(!e)return[];const r=(u,c)=>t(u)-t(c),i=(u,c)=>t(c)-t(u);return e.slice().sort(n===!0?i:r)},te=(e,t,n="asc")=>{if(!e)return[];const r=(u,c)=>`${t(u)}`.localeCompare(t(c)),i=(u,c)=>`${t(c)}`.localeCompare(t(u));return e.slice().sort(n==="desc"?i:r)},ne=(e,t)=>e?e.reduce((n,r)=>{const i=t(r);return n[i]=(n[i]??0)+1,n},{}):{},re=(e,t,n)=>{if(!e)return[];if(t===void 0)return[...e];for(let r=0;rr)=>e.reduce((r,i)=>(r[t(i)]=n(i),r),{}),ie=(e,t,n)=>e?e.reduce((r,i,u)=>(n(i,u)&&r.push(t(i,u)),r),[]):[];function se(e,t){const n=t??(r=>r);return O(e,(r,i)=>n(r)>n(i)?r:i)}function ue(e,t){const n=t??(r=>r);return O(e,(r,i)=>n(r){const n=Math.ceil(e.length/t);return new Array(n).fill(null).map((r,i)=>e.slice(i*t,i*t+t))},oe=(e,t)=>{const n=e.reduce((r,i)=>{const u=t?t(i):i;return r[u]||(r[u]=i),r},{});return Object.values(n)};function*A(e,t,n=i=>i,r=1){const i=y(n)?n:()=>n,u=t?e:0,c=t??e;for(let o=u;o<=c&&(yield i(o),!(o+r>c));o+=r);}const C=(e,t,n,r)=>Array.from(A(e,t,n,r)),fe=e=>e.reduce((t,n)=>(t.push(...n),t),[]),le=(e,t,n)=>{if(!e||!t)return!1;const r=n??(u=>u),i=t.reduce((u,c)=>(u[r(c)]=!0,u),{});return e.some(u=>i[r(u)])},j=(e,t)=>e?e.reduce((n,r)=>{const[i,u]=n;return t(r)?[[...i,r],u]:[i,[...u,r]]},[[],[]]):[[],[]],ae=(e,t,n)=>!t&&!e?[]:t?e?n?e.reduce((r,i)=>{const u=t.find(c=>n(i)===n(c));return u?r.push(u):r.push(i),r},[]):e:[]:e,de=(e,t,n)=>{if(!e&&!t)return[];if(!t)return[...e];if(!e)return[t];for(let r=0;r{if(!e&&!t)return[];if(!e)return[t];if(!t)return[...e];const i=n?(o,a)=>n(o,a)===n(t,a):o=>o===t;return e.find(i)?e.filter((o,a)=>!i(o,a)):(r?.strategy??"append")==="append"?[...e,t]:[t,...e]},he=e=>e?.filter(t=>!!t)??[],R=(e,t,n)=>{let r=n;for(let i=1;i<=e;i++)r=t(r,i);return r},me=(e,t,n=r=>r)=>{if(!e?.length&&!t?.length)return[];if(e?.length===void 0)return[...t];if(!t?.length)return[...e];const r=t.reduce((i,u)=>(i[n(u)]=!0,i),{});return e.filter(i=>!r[n(i)])};function we(e,t){if(e.length===0)return e;const n=t%e.length;return n===0?e:[...e.slice(-n,e.length),...e.slice(0,-n)]}const ye=async(e,t,n)=>{const r=n!==void 0;if(!r&&e?.length<1)throw new Error("Cannot reduce empty array with no init value");const i=r?e:e.slice(1);let u=r?n:e[0];for(const[c,o]of i.entries())u=await t(u,o,c);return u},pe=async(e,t)=>{if(!e)return[];let n=[],r=0;for(const i of e){const u=await t(i,r++);n.push(u)}return n},be=async e=>{const t=[],n=(u,c)=>t.push({fn:u,rethrow:c?.rethrow??!1}),[r,i]=await m(e)(n);for(const{fn:u,rethrow:c}of t){const[o]=await m(u)(r);if(o&&c)throw o}if(r)throw r;return i};class L extends Error{constructor(t=[]){super();const n=t.find(r=>r.name)?.name??"";this.name=`AggregateError(${n}...)`,this.message=`AggregateError with ${t.length} errors`,this.stack=t.find(r=>r.stack)?.stack??this.stack,this.errors=t}}const ke=async(e,t,n)=>{const r=t.map((d,b)=>({index:b,item:d})),i=async d=>{const b=[];for(;;){const f=r.pop();if(!f)return d(b);const[l,g]=await m(n)(f.item);b.push({error:l,result:g,index:f.index})}},u=C(1,e).map(()=>new Promise(i)),c=await Promise.all(u),[o,a]=j(B(c.flat(),d=>d.index),d=>!!d.error);if(o.length>0)throw new L(o.map(d=>d.error));return a.map(d=>d.result)};async function Oe(e){const t=w(e)?e.map(i=>[null,i]):Object.entries(e),n=await Promise.all(t.map(([i,u])=>u.then(c=>({result:c,exc:null,key:i})).catch(c=>({result:null,exc:c,key:i})))),r=n.filter(i=>i.exc);if(r.length>0)throw new L(r.map(i=>i.exc));return w(e)?n.map(i=>i.result):n.reduce((i,u)=>({...i,[u.key]:u.result}),{})}const Ae=async(e,t)=>{const n=e?.times??3,r=e?.delay,i=e?.backoff??null;for(const u of A(1,n)){const[c,o]=await m(t)(a=>{throw{_exited:a}});if(!c)return o;if(c._exited)throw c._exited;if(u===n)throw c;r&&await $(r),i&&await $(i(u))}},$=e=>new Promise(t=>setTimeout(t,e)),m=e=>(...t)=>{try{const n=e(...t);return S(n)?n.then(r=>[void 0,r]).catch(r=>[r,void 0]):[void 0,n]}catch(n){return[n,void 0]}},Ce=(e,t)=>{const n=i=>{if(t&&!t(i))throw i},r=i=>i instanceof Promise;try{const i=e();return r(i)?i.catch(n):i}catch(i){return n(i)}};function $e(...e){return(...t)=>e.slice(1).reduce((n,r)=>r(n),e[0](...t))}function Pe(...e){return e.reverse().reduce((t,n)=>n(t))}const _e=(e,...t)=>(...n)=>e(...t,...n),Ee=(e,t)=>n=>e({...t,...n}),Ne=e=>new Proxy({},{get:(t,n)=>e(n)}),Te=(e,t,n,r)=>function(...u){const c=n?n(...u):JSON.stringify({args:u}),o=e[c];if(o!==void 0&&(!o.exp||o.exp>new Date().getTime()))return o.value;const a=t(...u);return e[c]={exp:r?new Date().getTime()+r:null,value:a},a},Se=(e,t={})=>Te({},e,t.key??null,t.ttl??null),ze=({delay:e},t)=>{let n,r=!0;const i=(...u)=>{r?(clearTimeout(n),n=setTimeout(()=>{r&&t(...u),n=void 0},e)):t(...u)};return i.isPending=()=>n!==void 0,i.cancel=()=>{r=!1},i.flush=(...u)=>t(...u),i},Be=({interval:e},t)=>{let n=!0,r;const i=(...u)=>{n&&(t(...u),n=!1,r=setTimeout(()=>{n=!0,r=void 0},e))};return i.isThrottled=()=>r!==void 0,i},Me=(e,t)=>{const n=()=>{};return new Proxy(Object.assign(n,e),{get:(r,i)=>r[i],set:(r,i,u)=>(r[i]=u,!0),apply:(r,i,u)=>t(Object.assign({},r))(...u)})};function je(e,t,n){return typeof e=="number"&&typeof t=="number"&&(typeof n>"u"||typeof n=="number")?(typeof n>"u"&&(n=t,t=0),e>=Math.min(t,n)&&e{const n=t===void 0?0:t;if(e==null)return n;const r=parseFloat(e);return isNaN(r)?n:r},Z=(e,t)=>{const n=t===void 0?0:t;if(e==null)return n;const r=parseInt(e);return isNaN(r)?n:r},Le=(e,t=n=>n===void 0)=>e?Object.keys(e).reduce((r,i)=>(t(e[i])||(r[i]=e[i]),r),{}):{},P=(e,t)=>Object.keys(e).reduce((r,i)=>(r[t(i,e[i])]=e[i],r),{}),Ze=(e,t)=>Object.keys(e).reduce((r,i)=>(r[i]=t(e[i],i),r),{}),De=(e,t)=>e?Object.entries(e).reduce((n,[r,i])=>{const[u,c]=t(r,i);return n[u]=c,n},{}):{},Fe=e=>e?Object.keys(e).reduce((n,r)=>(n[e[r]]=r,n),{}):{},qe=e=>P(e,t=>t.toLowerCase()),Ie=e=>P(e,t=>t.toUpperCase()),D=e=>{if(N(e))return e;if(typeof e=="function")return e.bind({});const t=new e.constructor;return Object.getOwnPropertyNames(e).forEach(n=>{t[n]=e[n]}),t},ve=(e,t)=>{if(!e)return[];const n=Object.entries(e);return n.length===0?[]:n.reduce((r,i)=>(r.push(t(i[0],i[1])),r),[])},F=(e,t)=>e?t.reduce((n,r)=>(Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]),n),{}):{},Ue=(e,t=()=>!0)=>e?F(e,Object.keys(e).filter(n=>t(e[n]))):{},Ke=(e,t)=>e?!t||t.length===0?e:t.reduce((n,r)=>(delete n[r],n),{...e}):{},q=(e,t,n)=>{const r=t.split(/[\.\[\]]/g);let i=e;for(const u of r){if(i===null||i===void 0)return n;const c=u.replace(/['"]/g,"");c.trim()!==""&&(i=i[c])}return i===void 0?n:i},I=(e,t,n)=>{if(!e)return{};if(!t||n===void 0)return e;const r=t.split(/[\.\[\]]/g).filter(c=>!!c.trim()),i=c=>{if(r.length>1){const o=r.shift(),a=Z(r[0],null)!==null;c[o]=c[o]===void 0?a?[]:{}:c[o],i(c[o])}else c[r[0]]=n},u=D(e);return i(u),u},v=(e,t)=>!e||!t?e??t??{}:Object.entries({...e,...t}).reduce((n,[r,i])=>({...n,[r]:(()=>k(e[r])?v(e[r],i):i)()}),{}),U=e=>{if(!e)return[];const t=(n,r)=>k(n)?Object.entries(n).flatMap(([i,u])=>t(u,[...r,i])):w(n)?n.flatMap((i,u)=>t(i,[...r,`${u}`])):[r.join(".")];return t(e,[])},We=e=>e?M(U(e),t=>t,t=>q(e,t)):{},Je=e=>e?Object.keys(e).reduce((t,n)=>I(t,n,e[n]),{}):{},_=(e,t)=>Math.floor(Math.random()*(t-e+1)+e),Xe=e=>{const t=e.length;if(t===0)return null;const n=_(0,t-1);return e[n]},Ye=e=>e.map(t=>({rand:Math.random(),value:t})).sort((t,n)=>t.rand-n.rand).map(t=>t.value),He=(e,t="")=>{const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"+t;return R(e,r=>r+n.charAt(_(0,n.length-1)),"")},Qe=(e,t=n=>`${n}`)=>{const{indexesByKey:n,itemsByIndex:r}=e.reduce((f,l,g)=>({indexesByKey:{...f.indexesByKey,[t(l)]:g},itemsByIndex:{...f.itemsByIndex,[g]:l}}),{indexesByKey:{},itemsByIndex:{}}),i=(f,l)=>n[t(f)]n[t(f)]>n[t(l)]?f:l,c=()=>r[0],o=()=>r[e.length-1],a=(f,l)=>r[n[t(f)]+1]??l??c(),d=(f,l)=>r[n[t(f)]-1]??l??o();return{min:i,max:u,first:c,last:o,next:a,previous:d,spin:(f,l)=>{if(l===0)return f;const g=Math.abs(l),it=g>e.length?g%e.length:g;return C(0,it-1).reduce(K=>l>0?a(K):d(K),f)}}},p=e=>{if(!e||e.length===0)return"";const t=e.toLowerCase();return t.substring(0,1).toUpperCase()+t.substring(1,t.length)},Ve=e=>{const t=e?.replace(/([A-Z])+/g,p)?.split(/(?=[A-Z])|[\.\-\s_]/).map(n=>n.toLowerCase())??[];return t.length===0?"":t.length===1?t[0]:t.reduce((n,r)=>`${n}${r.charAt(0).toUpperCase()}${r.slice(1)}`)},Ge=(e,t)=>{const n=e?.replace(/([A-Z])+/g,p).split(/(?=[A-Z])|[\.\-\s_]/).map(i=>i.toLowerCase())??[];if(n.length===0)return"";if(n.length===1)return n[0];const r=n.reduce((i,u)=>`${i}_${u.toLowerCase()}`);return t?.splitOnNumber===!1?r:r.replace(/([A-Za-z]{1}[0-9]{1})/,i=>`${i[0]}_${i[1]}`)},xe=e=>{const t=e?.replace(/([A-Z])+/g,p)?.split(/(?=[A-Z])|[\.\-\s_]/).map(n=>n.toLowerCase())??[];return t.length===0?"":t.length===1?t[0]:t.reduce((n,r)=>`${n}-${r.toLowerCase()}`)},et=e=>{const t=e?.split(/[\.\-\s_]/).map(n=>n.toLowerCase())??[];return t.length===0?"":t.map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("")},tt=e=>e?e.split(/(?=[A-Z])|[\.\-\s_]/).map(t=>t.trim()).filter(t=>!!t).map(t=>p(t.toLowerCase())).join(" "):"",nt=(e,t,n=/\{\{(.+?)\}\}/g)=>Array.from(e.matchAll(n)).reduce((r,i)=>r.replace(i[0],t[i[1]]),e),rt=(e,t=" ")=>{if(!e)return"";const n=t.replace(/[\W]{1}/g,"\\$&"),r=new RegExp(`^[${n}]+|[${n}]+$`,"g");return e.replace(r,"")};return s.all=Oe,s.alphabetical=te,s.assign=v,s.boil=O,s.callable=Me,s.camel=Ve,s.capitalize=p,s.chain=$e,s.clone=D,s.cluster=ce,s.compose=Pe,s.construct=Je,s.counting=ne,s.crush=We,s.dash=xe,s.debounce=ze,s.defer=be,s.diff=me,s.draw=Xe,s.first=x,s.flat=fe,s.fork=j,s.get=q,s.group=H,s.guard=Ce,s.inRange=je,s.intersects=le,s.invert=Fe,s.isArray=w,s.isDate=T,s.isEmpty=Y,s.isEqual=z,s.isFloat=X,s.isFunction=y,s.isInt=J,s.isNumber=h,s.isObject=k,s.isPrimitive=N,s.isPromise=S,s.isString=W,s.isSymbol=E,s.iterate=R,s.keys=U,s.last=ee,s.list=C,s.listify=ve,s.lowerize=qe,s.map=pe,s.mapEntries=De,s.mapKeys=P,s.mapValues=Ze,s.max=se,s.memo=Se,s.merge=ae,s.min=ue,s.objectify=M,s.omit=Ke,s.parallel=ke,s.partial=_e,s.partob=Ee,s.pascal=et,s.pick=F,s.pickBy=Ue,s.proxied=Ne,s.random=_,s.range=A,s.reduce=ye,s.replace=re,s.replaceOrAppend=de,s.retry=Ae,s.select=ie,s.series=Qe,s.set=I,s.shake=Le,s.shift=we,s.shuffle=Ye,s.sift=he,s.sleep=$,s.snake=Ge,s.sort=B,s.sum=G,s.template=nt,s.throttle=Be,s.title=tt,s.toFloat=Re,s.toInt=Z,s.toggle=ge,s.trim=rt,s.try=m,s.tryit=m,s.uid=He,s.unique=oe,s.upperize=Ie,s.zip=Q,s.zipToObject=V,s}({}); diff --git a/docs/object/pick-by.mdx b/docs/object/pick-by.mdx new file mode 100644 index 00000000..75803c34 --- /dev/null +++ b/docs/object/pick-by.mdx @@ -0,0 +1,22 @@ +--- +title: pickBy +description: Pick only the desired attributes from an object +group: Object +--- + +## Basic usage + +Given an object and an identity function, returns a new object with only the values which makes identity returns true. + +```ts +import { pickBy } from 'radash' + +const fish = { + name: 'Bass', + weight: 8, + source: 'lake', + barckish: false +} + +pick(fish, v => v === 8) // => { weight } +``` diff --git a/package.json b/package.json index 0f7a54c7..472a9a5c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "radash", - "version": "12.1.0", + "version": "12.2.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 9dff2e21..092f9c3e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -69,6 +69,7 @@ export { mapValues, omit, pick, + pickBy, set, shake, upperize diff --git a/src/object.ts b/src/object.ts index 5561da2a..b51653d7 100644 --- a/src/object.ts +++ b/src/object.ts @@ -181,6 +181,24 @@ export const pick = ( }, {} as Pick) } +/** + * Picks properties of an object based on a predicate function. + * + * @param {T} obj - The object from which to pick properties. + * @param {function} predicate - The function used to filter the object's properties. + * @return {object} A new object with properties picked based on the predicate. + */ +export const pickBy = ( + obj: T, + predicate: (value: T[TKeys]) => boolean = () => true +): Pick => { + if (!obj) return {} as Pick + return pick( + obj, + (Object.keys(obj) as TKeys[]).filter(key => predicate(obj[key])) + ) +} + /** * Omit a list of properties from an object * returning a new object with the properties diff --git a/src/tests/async.test.ts b/src/tests/async.test.ts index e67aa3d0..aeaa6b32 100644 --- a/src/tests/async.test.ts +++ b/src/tests/async.test.ts @@ -2,6 +2,11 @@ import { assert } from 'chai' import * as _ from '..' import { AggregateError } from '../async' +// fix error of calling useFakeTimers on nodejs version v20.12.1 https://stackoverflow.com/a/77694958/5131623 +// Object.defineProperty(global, 'performance', { +// writable: true +// }) + describe('async module', () => { beforeEach(() => jest.useFakeTimers({ advanceTimers: true })) diff --git a/src/tests/object.test.ts b/src/tests/object.test.ts index 42cc1e22..01f4bb8c 100644 --- a/src/tests/object.test.ts +++ b/src/tests/object.test.ts @@ -282,6 +282,23 @@ describe('object module', () => { }) }) + describe('pickBy function', () => { + test('handles null input', () => { + const result = _.pickBy(null as unknown as Record) + assert.deepEqual(result, {}) + }) + + test('handles no identity function', () => { + const result = _.pickBy({ a: 2 }) + assert.deepEqual(result, { a: 2 }) + }) + + test('returns picked properties only', () => { + const result = _.pickBy({ a: 1, b: 2, c: 3, d: 4 }, v => v % 2 === 0) + assert.deepEqual(result, { b: 2, d: 4 } as any) + }) + }) + describe('omit function', () => { const person = { name: 'jay',