From 0cefc6da1ad4efb8254606521269c446e0e92eeb Mon Sep 17 00:00:00 2001 From: shtse8 Date: Thu, 14 Mar 2024 17:36:05 +0800 Subject: [PATCH] Add isKeyOf function for checking if a value is a key of an object --- cdn/radash.esm.js | 5 ++++- cdn/radash.js | 4 ++++ cdn/radash.min.js | 2 +- docs/typed/is-key-of.mdx | 21 +++++++++++++++++++++ src/index.ts | 1 + src/tests/typed.test.ts | 13 +++++++++++++ src/typed.ts | 13 +++++++++++++ 7 files changed, 57 insertions(+), 2 deletions(-) create mode 100644 docs/typed/is-key-of.mdx diff --git a/cdn/radash.esm.js b/cdn/radash.esm.js index 8c634803..5575fdbc 100644 --- a/cdn/radash.esm.js +++ b/cdn/radash.esm.js @@ -91,6 +91,9 @@ const isNullish = (value) => { const isNonNullish = (value) => { return value !== null && value !== void 0; }; +const isKeyOf = (value, obj) => { + return value in obj; +}; const group = (array, getGroupId) => { return array.reduce((acc, item) => { @@ -943,4 +946,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, isNonNullish, isNullish, 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, isKeyOf, isNonNullish, isNullish, 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 }; diff --git a/cdn/radash.js b/cdn/radash.js index 535240e7..ffeaf401 100644 --- a/cdn/radash.js +++ b/cdn/radash.js @@ -94,6 +94,9 @@ var radash = (function (exports) { const isNonNullish = (value) => { return value !== null && value !== void 0; }; + const isKeyOf = (value, obj) => { + return value in obj; + }; const group = (array, getGroupId) => { return array.reduce((acc, item) => { @@ -981,6 +984,7 @@ var radash = (function (exports) { exports.isFloat = isFloat; exports.isFunction = isFunction; exports.isInt = isInt; + exports.isKeyOf = isKeyOf; exports.isNonNullish = isNonNullish; exports.isNullish = isNullish; exports.isNumber = isNumber; diff --git a/cdn/radash.min.js b/cdn/radash.min.js index 548346cd..714e8d06 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,w=Array.isArray,k=t=>!!t&&t.constructor===Object,E=t=>t==null||typeof t!="object"&&typeof t!="function",y=t=>!!(t&&t.constructor&&t.call&&t.apply),K=t=>typeof t=="string"||t instanceof String,W=t=>h(t)&&t%1===0,J=t=>h(t)&&t%1!==0,h=t=>{try{return Number(t)===t}catch{return!1}},T=t=>Object.prototype.toString.call(t)==="[object Date]",S=t=>!(!t||!t.then||!y(t.then)),X=t=>{if(t===!0||t===!1||t==null)return!0;if(h(t))return t===0;if(T(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},j=(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==null,H=t=>t!=null,Q=(t,e)=>t.reduce((n,r)=>{const i=e(r);return n[i]||(n[i]=[]),n[i].push(r),n},{});function V(...t){return!t||!t.length?[]:new Array(Math.max(...t.map(({length:e})=>e))).fill([]).map((e,n)=>t.map(r=>r[n]))}function G(t,e){if(!t||!t.length)return{};const n=y(e)?e:w(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);function x(t,e){return(t||[]).reduce((n,r)=>n+(e?e(r):r),0)}const tt=(t,e=void 0)=>t?.length>0?t[0]:e,et=(t,e=void 0)=>t?.length>0?t[t.length-1]:e,z=(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)},nt=(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)},rt=(t,e)=>t?t.reduce((n,r)=>{const i=e(r);return n[i]=(n[i]??0)+1,n},{}):{},it=(t,e,n)=>{if(!t)return[];if(e===void 0)return[...t];for(let r=0;rr)=>t.reduce((r,i)=>(r[e(i)]=n(i),r),{}),st=(t,e,n)=>t?t.reduce((r,i,u)=>(n(i,u)&&r.push(e(i,u)),r),[]):[];function ut(t,e){const n=e??(r=>r);return O(t,(r,i)=>n(r)>n(i)?r:i)}function ct(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))},lt=(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 N=(t,e,n,r)=>Array.from(A(t,e,n,r)),ft=t=>t.reduce((e,n)=>(e.push(...n),e),[]),at=(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)])},R=(t,e)=>t?t.reduce((n,r)=>{const[i,u]=n;return e(r)?[[...i,r],u]:[i,[...u,r]]},[[],[]]):[[],[]],dt=(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,gt=(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,a)=>n(o,a)===n(e,a):o=>o===e;return t.find(i)?t.filter((o,a)=>!i(o,a)):(r?.strategy??"append")==="append"?[...t,e]:[e,...t]},mt=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},wt=(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 yt(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 pt=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,o]of i.entries())u=await e(u,o,c);return u},bt=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},kt=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(o&&c)throw o}if(r)throw r;return i};class L 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 Ot=async(t,e,n)=>{const r=e.map((d,b)=>({index:b,item:d})),i=async d=>{const b=[];for(;;){const l=r.pop();if(!l)return d(b);const[f,g]=await m(n)(l.item);b.push({error:f,result:g,index:l.index})}},u=N(1,t).map(()=>new Promise(i)),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 At(t){const e=w(t)?t.map(i=>[null,i]):Object.entries(t),n=await Promise.all(e.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(t)?n.map(i=>i.result):n.reduce((i,u)=>({...i,[u.key]:u.result}),{})}const Nt=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)(a=>{throw{_exited:a}});if(!c)return o;if(c._exited)throw c._exited;if(u===n)throw c;r&&await C(r),i&&await C(i(u))}},C=t=>new Promise(e=>setTimeout(e,t)),m=t=>(...e)=>{try{const n=t(...e);return S(n)?n.then(r=>[void 0,r]).catch(r=>[r,void 0]):[void 0,n]}catch(n){return[n,void 0]}},Ct=(t,e)=>{const n=i=>{if(e&&!e(i))throw i},r=i=>i instanceof Promise;try{const i=t();return r(i)?i.catch(n):i}catch(i){return n(i)}};function $t(...t){return(...e)=>t.slice(1).reduce((n,r)=>r(n),t[0](...e))}function Pt(...t){return t.reverse().reduce((e,n)=>n(e))}const _t=(t,...e)=>(...n)=>t(...e,...n),Et=(t,e)=>n=>t({...e,...n}),Tt=t=>new Proxy({},{get:(e,n)=>t(n)}),St=(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 a=e(...u);return t[c]={exp:r?new Date().getTime()+r:null,value:a},a},jt=(t,e={})=>St({},t,e.key??null,e.ttl??null),zt=({delay:t},e)=>{let n,r=!0;const i=(...u)=>{r?(clearTimeout(n),n=setTimeout(()=>{r&&e(...u),n=void 0},t)):e(...u)};return i.isPending=()=>n!==void 0,i.cancel=()=>{r=!1},i.flush=(...u)=>e(...u),i},Mt=({interval:t},e)=>{let n=!0,r;const i=(...u)=>{n&&(e(...u),n=!1,r=setTimeout(()=>{n=!0,r=void 0},t))};return i.isThrottled=()=>r!==void 0,i},Rt=(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)})};function Bt(t,e,n){return typeof t=="number"&&typeof e=="number"&&(typeof n>"u"||typeof n=="number")?(typeof n>"u"&&(n=e,e=0),t>=Math.min(e,n)&&t{const n=e===void 0?0:e;if(t==null)return n;const r=parseFloat(t);return isNaN(r)?n:r},Z=(t,e)=>{const n=e===void 0?0:e;if(t==null)return n;const r=parseInt(t);return isNaN(r)?n:r},Zt=(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),{}),Dt=(t,e)=>Object.keys(t).reduce((r,i)=>(r[i]=e(t[i],i),r),{}),Ft=(t,e)=>t?Object.entries(t).reduce((n,[r,i])=>{const[u,c]=e(r,i);return n[u]=c,n},{}):{},qt=t=>t?Object.keys(t).reduce((n,r)=>(n[t[r]]=r,n),{}):{},It=t=>$(t,e=>e.toLowerCase()),vt=t=>$(t,e=>e.toUpperCase()),D=t=>{if(E(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},Ut=(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),[])},Kt=(t,e)=>t?e.reduce((n,r)=>(Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=t[r]),n),{}):{},Wt=(t,e)=>t?!e||e.length===0?t:e.reduce((n,r)=>(delete n[r],n),{...t}):{},F=(t,e,n)=>{const r=e.split(/[\.\[\]]/g);let i=t;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},q=(t,e,n)=>{if(!t)return{};if(!e||n===void 0)return t;const r=e.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(t);return i(u),u},I=(t,e)=>!t||!e?t??e??{}:Object.entries({...t,...e}).reduce((n,[r,i])=>({...n,[r]:(()=>k(t[r])?I(t[r],i):i)()}),{}),v=t=>{if(!t)return[];const e=(n,r)=>k(n)?Object.entries(n).flatMap(([i,u])=>e(u,[...r,i])):w(n)?n.flatMap((i,u)=>e(i,[...r,`${u}`])):[r.join(".")];return e(t,[])},Jt=t=>t?M(v(t),e=>e,e=>F(t,e)):{},Xt=t=>t?Object.keys(t).reduce((e,n)=>q(e,n,t[n]),{}):{},P=(t,e)=>Math.floor(Math.random()*(e-t+1)+t),Yt=t=>{const e=t.length;if(e===0)return null;const n=P(0,e-1);return t[n]},Ht=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(P(0,n.length-1)),"")},Vt=(t,e=n=>`${n}`)=>{const{indexesByKey:n,itemsByIndex:r}=t.reduce((l,f,g)=>({indexesByKey:{...l.indexesByKey,[e(f)]:g},itemsByIndex:{...l.itemsByIndex,[g]:f}}),{indexesByKey:{},itemsByIndex:{}}),i=(l,f)=>n[e(l)]n[e(l)]>n[e(f)]?l:f,c=()=>r[0],o=()=>r[t.length-1],a=(l,f)=>r[n[e(l)]+1]??f??c(),d=(l,f)=>r[n[e(l)]-1]??f??o();return{min:i,max:u,first:c,last:o,next:a,previous:d,spin:(l,f)=>{if(f===0)return l;const g=Math.abs(f),se=g>t.length?g%t.length:g;return N(0,se-1).reduce(U=>f>0?a(U):d(U),l)}}},p=t=>{if(!t||t.length===0)return"";const e=t.toLowerCase();return e.substring(0,1).toUpperCase()+e.substring(1,e.length)},Gt=t=>{const e=t?.replace(/([A-Z])+/g,p)?.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)}`)},xt=(t,e)=>{const n=t?.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 e?.splitOnNumber===!1?r:r.replace(/([A-Za-z]{1}[0-9]{1})/,i=>`${i[0]}_${i[1]}`)},te=t=>{const e=t?.replace(/([A-Z])+/g,p)?.split(/(?=[A-Z])|[\.\-\s_]/).map(n=>n.toLowerCase())??[];return e.length===0?"":e.length===1?e[0]:e.reduce((n,r)=>`${n}-${r.toLowerCase()}`)},ee=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("")},ne=t=>t?t.split(/(?=[A-Z])|[\.\-\s_]/).map(e=>e.trim()).filter(e=>!!e).map(e=>p(e.toLowerCase())).join(" "):"",re=(t,e,n=/\{\{(.+?)\}\}/g)=>Array.from(t.matchAll(n)).reduce((r,i)=>r.replace(i[0],e[i[1]]),t),ie=(t,e=" ")=>{if(!t)return"";const n=e.replace(/[\W]{1}/g,"\\$&"),r=new RegExp(`^[${n}]+|[${n}]+$`,"g");return t.replace(r,"")};return s.all=At,s.alphabetical=nt,s.assign=I,s.boil=O,s.callable=Rt,s.camel=Gt,s.capitalize=p,s.chain=$t,s.clone=D,s.cluster=ot,s.compose=Pt,s.construct=Xt,s.counting=rt,s.crush=Jt,s.dash=te,s.debounce=zt,s.defer=kt,s.diff=wt,s.draw=Yt,s.first=tt,s.flat=ft,s.fork=R,s.get=F,s.group=Q,s.guard=Ct,s.inRange=Bt,s.intersects=at,s.invert=qt,s.isArray=w,s.isDate=T,s.isEmpty=X,s.isEqual=j,s.isFloat=J,s.isFunction=y,s.isInt=W,s.isNonNullish=H,s.isNullish=Y,s.isNumber=h,s.isObject=k,s.isPrimitive=E,s.isPromise=S,s.isString=K,s.isSymbol=_,s.iterate=B,s.keys=v,s.last=et,s.list=N,s.listify=Ut,s.lowerize=It,s.map=bt,s.mapEntries=Ft,s.mapKeys=$,s.mapValues=Dt,s.max=ut,s.memo=jt,s.merge=dt,s.min=ct,s.objectify=M,s.omit=Wt,s.parallel=Ot,s.partial=_t,s.partob=Et,s.pascal=ee,s.pick=Kt,s.proxied=Tt,s.random=P,s.range=A,s.reduce=pt,s.replace=it,s.replaceOrAppend=gt,s.retry=Nt,s.select=st,s.series=Vt,s.set=q,s.shake=Zt,s.shift=yt,s.shuffle=Ht,s.sift=mt,s.sleep=C,s.snake=xt,s.sort=z,s.sum=x,s.template=re,s.throttle=Mt,s.title=ne,s.toFloat=Lt,s.toInt=Z,s.toggle=ht,s.trim=ie,s.try=m,s.tryit=m,s.uid=Qt,s.unique=lt,s.upperize=vt,s.zip=V,s.zipToObject=G,s}({}); +var radash=function(s){"use strict";const _=t=>!!t&&t.constructor===Symbol,w=Array.isArray,O=t=>!!t&&t.constructor===Object,E=t=>t==null||typeof t!="object"&&typeof t!="function",y=t=>!!(t&&t.constructor&&t.call&&t.apply),K=t=>typeof t=="string"||t instanceof String,W=t=>h(t)&&t%1===0,J=t=>h(t)&&t%1!==0,h=t=>{try{return Number(t)===t}catch{return!1}},T=t=>Object.prototype.toString.call(t)==="[object Date]",S=t=>!(!t||!t.then||!y(t.then)),X=t=>{if(t===!0||t===!1||t==null)return!0;if(h(t))return t===0;if(T(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},j=(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==null,H=t=>t!=null,Q=(t,e)=>t in e,V=(t,e)=>t.reduce((n,r)=>{const i=e(r);return n[i]||(n[i]=[]),n[i].push(r),n},{});function G(...t){return!t||!t.length?[]:new Array(Math.max(...t.map(({length:e})=>e))).fill([]).map((e,n)=>t.map(r=>r[n]))}function x(t,e){if(!t||!t.length)return{};const n=y(e)?e:w(e)?(r,i)=>e[i]:(r,i)=>e;return t.reduce((r,i,u)=>(r[i]=n(i,u),r),{})}const k=(t,e)=>!t||(t.length??0)===0?null:t.reduce(e);function tt(t,e){return(t||[]).reduce((n,r)=>n+(e?e(r):r),0)}const et=(t,e=void 0)=>t?.length>0?t[0]:e,nt=(t,e=void 0)=>t?.length>0?t[t.length-1]:e,z=(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)},rt=(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)},it=(t,e)=>t?t.reduce((n,r)=>{const i=e(r);return n[i]=(n[i]??0)+1,n},{}):{},st=(t,e,n)=>{if(!t)return[];if(e===void 0)return[...t];for(let r=0;rr)=>t.reduce((r,i)=>(r[e(i)]=n(i),r),{}),ut=(t,e,n)=>t?t.reduce((r,i,u)=>(n(i,u)&&r.push(e(i,u)),r),[]):[];function ct(t,e){const n=e??(r=>r);return k(t,(r,i)=>n(r)>n(i)?r:i)}function ot(t,e){const n=e??(r=>r);return k(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))},lt=(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 N=(t,e,n,r)=>Array.from(A(t,e,n,r)),at=t=>t.reduce((e,n)=>(e.push(...n),e),[]),dt=(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)])},R=(t,e)=>t?t.reduce((n,r)=>{const[i,u]=n;return e(r)?[[...i,r],u]:[i,[...u,r]]},[[],[]]):[[],[]],gt=(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,ht=(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,a)=>n(o,a)===n(e,a):o=>o===e;return t.find(i)?t.filter((o,a)=>!i(o,a)):(r?.strategy??"append")==="append"?[...t,e]:[e,...t]},wt=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},yt=(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 pt(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 bt=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,o]of i.entries())u=await e(u,o,c);return u},Ot=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},kt=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(o&&c)throw o}if(r)throw r;return i};class L 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 At=async(t,e,n)=>{const r=e.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=N(1,t).map(()=>new Promise(i)),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 Nt(t){const e=w(t)?t.map(i=>[null,i]):Object.entries(t),n=await Promise.all(e.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(t)?n.map(i=>i.result):n.reduce((i,u)=>({...i,[u.key]:u.result}),{})}const Ct=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)(a=>{throw{_exited:a}});if(!c)return o;if(c._exited)throw c._exited;if(u===n)throw c;r&&await C(r),i&&await C(i(u))}},C=t=>new Promise(e=>setTimeout(e,t)),m=t=>(...e)=>{try{const n=t(...e);return S(n)?n.then(r=>[void 0,r]).catch(r=>[r,void 0]):[void 0,n]}catch(n){return[n,void 0]}},$t=(t,e)=>{const n=i=>{if(e&&!e(i))throw i},r=i=>i instanceof Promise;try{const i=t();return r(i)?i.catch(n):i}catch(i){return n(i)}};function Pt(...t){return(...e)=>t.slice(1).reduce((n,r)=>r(n),t[0](...e))}function _t(...t){return t.reverse().reduce((e,n)=>n(e))}const Et=(t,...e)=>(...n)=>t(...e,...n),Tt=(t,e)=>n=>t({...e,...n}),St=t=>new Proxy({},{get:(e,n)=>t(n)}),jt=(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 a=e(...u);return t[c]={exp:r?new Date().getTime()+r:null,value:a},a},zt=(t,e={})=>jt({},t,e.key??null,e.ttl??null),Mt=({delay:t},e)=>{let n,r=!0;const i=(...u)=>{r?(clearTimeout(n),n=setTimeout(()=>{r&&e(...u),n=void 0},t)):e(...u)};return i.isPending=()=>n!==void 0,i.cancel=()=>{r=!1},i.flush=(...u)=>e(...u),i},Rt=({interval:t},e)=>{let n=!0,r;const i=(...u)=>{n&&(e(...u),n=!1,r=setTimeout(()=>{n=!0,r=void 0},t))};return i.isThrottled=()=>r!==void 0,i},Bt=(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)})};function Lt(t,e,n){return typeof t=="number"&&typeof e=="number"&&(typeof n>"u"||typeof n=="number")?(typeof n>"u"&&(n=e,e=0),t>=Math.min(e,n)&&t{const n=e===void 0?0:e;if(t==null)return n;const r=parseFloat(t);return isNaN(r)?n:r},Z=(t,e)=>{const n=e===void 0?0:e;if(t==null)return n;const r=parseInt(t);return isNaN(r)?n:r},Dt=(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),{}),Ft=(t,e)=>Object.keys(t).reduce((r,i)=>(r[i]=e(t[i],i),r),{}),qt=(t,e)=>t?Object.entries(t).reduce((n,[r,i])=>{const[u,c]=e(r,i);return n[u]=c,n},{}):{},It=t=>t?Object.keys(t).reduce((n,r)=>(n[t[r]]=r,n),{}):{},vt=t=>$(t,e=>e.toLowerCase()),Ut=t=>$(t,e=>e.toUpperCase()),D=t=>{if(E(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},Kt=(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),[])},Wt=(t,e)=>t?e.reduce((n,r)=>(Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=t[r]),n),{}):{},Jt=(t,e)=>t?!e||e.length===0?t:e.reduce((n,r)=>(delete n[r],n),{...t}):{},F=(t,e,n)=>{const r=e.split(/[\.\[\]]/g);let i=t;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},q=(t,e,n)=>{if(!t)return{};if(!e||n===void 0)return t;const r=e.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(t);return i(u),u},I=(t,e)=>!t||!e?t??e??{}:Object.entries({...t,...e}).reduce((n,[r,i])=>({...n,[r]:(()=>O(t[r])?I(t[r],i):i)()}),{}),v=t=>{if(!t)return[];const e=(n,r)=>O(n)?Object.entries(n).flatMap(([i,u])=>e(u,[...r,i])):w(n)?n.flatMap((i,u)=>e(i,[...r,`${u}`])):[r.join(".")];return e(t,[])},Xt=t=>t?M(v(t),e=>e,e=>F(t,e)):{},Yt=t=>t?Object.keys(t).reduce((e,n)=>q(e,n,t[n]),{}):{},P=(t,e)=>Math.floor(Math.random()*(e-t+1)+t),Ht=t=>{const e=t.length;if(e===0)return null;const n=P(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),Vt=(t,e="")=>{const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"+e;return B(t,r=>r+n.charAt(P(0,n.length-1)),"")},Gt=(t,e=n=>`${n}`)=>{const{indexesByKey:n,itemsByIndex:r}=t.reduce((f,l,g)=>({indexesByKey:{...f.indexesByKey,[e(l)]:g},itemsByIndex:{...f.itemsByIndex,[g]:l}}),{indexesByKey:{},itemsByIndex:{}}),i=(f,l)=>n[e(f)]n[e(f)]>n[e(l)]?f:l,c=()=>r[0],o=()=>r[t.length-1],a=(f,l)=>r[n[e(f)]+1]??l??c(),d=(f,l)=>r[n[e(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),ue=g>t.length?g%t.length:g;return N(0,ue-1).reduce(U=>l>0?a(U):d(U),f)}}},p=t=>{if(!t||t.length===0)return"";const e=t.toLowerCase();return e.substring(0,1).toUpperCase()+e.substring(1,e.length)},xt=t=>{const e=t?.replace(/([A-Z])+/g,p)?.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)}`)},te=(t,e)=>{const n=t?.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 e?.splitOnNumber===!1?r:r.replace(/([A-Za-z]{1}[0-9]{1})/,i=>`${i[0]}_${i[1]}`)},ee=t=>{const e=t?.replace(/([A-Z])+/g,p)?.split(/(?=[A-Z])|[\.\-\s_]/).map(n=>n.toLowerCase())??[];return e.length===0?"":e.length===1?e[0]:e.reduce((n,r)=>`${n}-${r.toLowerCase()}`)},ne=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("")},re=t=>t?t.split(/(?=[A-Z])|[\.\-\s_]/).map(e=>e.trim()).filter(e=>!!e).map(e=>p(e.toLowerCase())).join(" "):"",ie=(t,e,n=/\{\{(.+?)\}\}/g)=>Array.from(t.matchAll(n)).reduce((r,i)=>r.replace(i[0],e[i[1]]),t),se=(t,e=" ")=>{if(!t)return"";const n=e.replace(/[\W]{1}/g,"\\$&"),r=new RegExp(`^[${n}]+|[${n}]+$`,"g");return t.replace(r,"")};return s.all=Nt,s.alphabetical=rt,s.assign=I,s.boil=k,s.callable=Bt,s.camel=xt,s.capitalize=p,s.chain=Pt,s.clone=D,s.cluster=ft,s.compose=_t,s.construct=Yt,s.counting=it,s.crush=Xt,s.dash=ee,s.debounce=Mt,s.defer=kt,s.diff=yt,s.draw=Ht,s.first=et,s.flat=at,s.fork=R,s.get=F,s.group=V,s.guard=$t,s.inRange=Lt,s.intersects=dt,s.invert=It,s.isArray=w,s.isDate=T,s.isEmpty=X,s.isEqual=j,s.isFloat=J,s.isFunction=y,s.isInt=W,s.isKeyOf=Q,s.isNonNullish=H,s.isNullish=Y,s.isNumber=h,s.isObject=O,s.isPrimitive=E,s.isPromise=S,s.isString=K,s.isSymbol=_,s.iterate=B,s.keys=v,s.last=nt,s.list=N,s.listify=Kt,s.lowerize=vt,s.map=Ot,s.mapEntries=qt,s.mapKeys=$,s.mapValues=Ft,s.max=ct,s.memo=zt,s.merge=gt,s.min=ot,s.objectify=M,s.omit=Jt,s.parallel=At,s.partial=Et,s.partob=Tt,s.pascal=ne,s.pick=Wt,s.proxied=St,s.random=P,s.range=A,s.reduce=bt,s.replace=st,s.replaceOrAppend=ht,s.retry=Ct,s.select=ut,s.series=Gt,s.set=q,s.shake=Dt,s.shift=pt,s.shuffle=Qt,s.sift=wt,s.sleep=C,s.snake=te,s.sort=z,s.sum=tt,s.template=ie,s.throttle=Rt,s.title=re,s.toFloat=Zt,s.toInt=Z,s.toggle=mt,s.trim=se,s.try=m,s.tryit=m,s.uid=Vt,s.unique=lt,s.upperize=Ut,s.zip=G,s.zipToObject=x,s}({}); diff --git a/docs/typed/is-key-of.mdx b/docs/typed/is-key-of.mdx new file mode 100644 index 00000000..d7466e5d --- /dev/null +++ b/docs/typed/is-key-of.mdx @@ -0,0 +1,21 @@ +--- +title: isKeyOf +description: 'Checks if the given value is a key of the given object. It is useful for narrowing down the type of a value.' +group: Typed +--- + +## Basic usage + +Pass the object and the value to check. It will return a boolean indicating if the value is a key of the object. + +```ts +import { isKeyOf } from 'radash' + +const obj = { + a: 1, + b: 2, + c: 3, +} +isKeyOf(obj, 'a') // true +isKeyOf(obj, 'd') // false +``` diff --git a/src/index.ts b/src/index.ts index da0f6aa6..eafec6e1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -93,6 +93,7 @@ export { isFloat, isFunction, isInt, + isKeyOf, isNonNullish, isNullish, isNumber, diff --git a/src/tests/typed.test.ts b/src/tests/typed.test.ts index fb4e444e..1f38b0f2 100644 --- a/src/tests/typed.test.ts +++ b/src/tests/typed.test.ts @@ -575,4 +575,17 @@ describe('typed module', () => { assert.isTrue(_.isNonNullish(new Date())) }) }) + + describe('isKeyOf function', () => { + test('returns true for keys of the object', () => { + const obj = { name: 'ray', age: 22 } + assert.isTrue(_.isKeyOf('name', obj)) + assert.isTrue(_.isKeyOf('age', obj)) + }) + test('returns false for keys not in the object', () => { + const obj = { name: 'ray', age: 22 } + assert.isFalse(_.isKeyOf('height', obj)) + assert.isFalse(_.isKeyOf('weight', obj)) + }) + }) }) diff --git a/src/typed.ts b/src/typed.ts index 3a605ad7..d4c6920f 100644 --- a/src/typed.ts +++ b/src/typed.ts @@ -120,3 +120,16 @@ export const isNonNullish = ( ): value is Exclude => { return value !== null && value !== undefined } + +/** + * Checks if the given value is a key of the given object. It is useful for narrowing down the type of a value. + * @param value key to check + * @param obj object to check + * @returns true if the value is a key of the object + */ +export const isKeyOf = >( + value: string | number | symbol, + obj: TType +): value is keyof TType => { + return value in obj +}