@stacksjs/collections 0.70.23 → 0.70.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -29,7 +29,7 @@ const collection = collect([{
29
29
  console.log(collection.avg('pages')) // 636
30
30
  ```
31
31
 
32
- To view the full documentation, please visit [https://stacksjs.org/collections](https://stacksjs.org/collections).
32
+ To view the full documentation, please visit [<https://stacksjs.com/collection>s](https://stacksjs.com/collections).
33
33
 
34
34
  ## 🧪 Testing
35
35
 
package/dist/index.js CHANGED
@@ -1,31 +1 @@
1
- var{create:P,defineProperty:B,getOwnPropertyDescriptor:I,getOwnPropertyNames:L,getPrototypeOf:C}=Object,F=Object.prototype.hasOwnProperty,z=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),U=(e,t)=>{for(var r in t)B(e,r,{get:t[r],enumerable:!0})},E=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let l of L(t))!F.call(e,l)&&l!==r&&B(e,l,{get:()=>t[l],enumerable:!(n=I(t,l))||n.enumerable});return e},H=(e,t,r)=>(E(e,t,"default"),r&&E(r,t,"default")),j=(e,t,r)=>(r=e!=null?P(C(e)):{},E(t||!e||!e.__esModule?B(r,"default",{value:e,enumerable:!0}):r,e)),q=z((e,t)=>{var r=t.exports={},n,l;function i(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?n=setTimeout:n=i}catch{n=i}try{typeof clearTimeout=="function"?l=clearTimeout:l=o}catch{l=o}})();function s(d){if(n===setTimeout)return setTimeout(d,0);if((n===i||!n)&&setTimeout)return n=setTimeout,setTimeout(d,0);try{return n(d,0)}catch{try{return n.call(null,d,0)}catch{return n.call(this,d,0)}}}function a(d){if(l===clearTimeout)return clearTimeout(d);if((l===o||!l)&&clearTimeout)return l=clearTimeout,clearTimeout(d);try{return l(d)}catch{try{return l.call(null,d)}catch{return l.call(this,d)}}}var u=[],m=!1,f,p=-1;function g(){!m||!f||(m=!1,f.length?u=f.concat(u):p=-1,u.length&&b())}function b(){if(!m){var d=s(g);m=!0;for(var M=u.length;M;){for(f=u,u=[];++p<M;)f&&f[p].run();p=-1,M=u.length}f=null,m=!1,a(d)}}r.nextTick=function(d){var M=new Array(arguments.length-1);if(arguments.length>1)for(var h=1;h<arguments.length;h++)M[h-1]=arguments[h];u.push(new v(d,M)),u.length===1&&!m&&s(b)};function v(d,M){this.fun=d,this.array=M}v.prototype.run=function(){this.fun.apply(null,this.array)},r.title="browser",r.browser=!0,r.env={},r.argv=[],r.version="",r.versions={};function A(){}r.on=A,r.addListener=A,r.once=A,r.off=A,r.removeListener=A,r.removeAllListeners=A,r.emit=A,r.prependListener=A,r.prependOnceListener=A,r.listeners=function(d){return[]},r.binding=function(d){throw new Error("process.binding is not supported")},r.cwd=function(){return"/"},r.chdir=function(d){throw new Error("process.chdir is not supported")},r.umask=function(){return 0}}),Q={};U(Q,{default:()=>k});H(Q,j(q()));var k=j(q());function S(e){let t=[],r=null,n=null;async function*l(){if(r){for(let o of r)yield o;return}let i=[];for await(let o of e){for(let s of t)if(o=s(o),o===void 0)break;if(o!==void 0)if(n){if(i.push(o),i.length>=n){for(let s of i)yield s;i=[]}}else yield o}if(i.length>0)for(let o of i)yield o}return{map(i){let o=0;return t.push((s)=>i(s,o++)),S(l())},filter(i){let o=0;return t.push((s)=>i(s,o++)?s:void 0),S(l())},flatMap(i){let o=0;return t.push((s)=>i(s,o++)),S(l())},take(i){let o=0;return t.push((s)=>o++<i?s:void 0),S(l())},skip(i){let o=0;return t.push((s)=>o++<i?void 0:s),S(l())},chunk(i){let o=[];return t.push((s)=>{if(o.push(s),o.length===i){let a=o;return o=[],a}return}),S(l())},async toArray(){if(r)return r;let i=[];for await(let o of l())i.push(o);return i},async toCollection(){let i=await this.toArray();return c(i)},async forEach(i){for await(let o of l())i(o)},async reduce(i,o){let s=o;for await(let a of l())s=i(s,a);return s},async count(){let i=0;for await(let o of l())i++;return i},async first(){let i=await l().next();return i.done?void 0:i.value},async last(){let i;for await(let o of l())i=o;return i},async nth(i){let o=0;for await(let s of l()){if(o===i)return s;o++}return},cache(){return this.toArray().then((i)=>{r=i}),this},batch(i){return n=i,this},pipe(i){return i(this)}}}function Z(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function W(e,t){let r=new Date(e);switch(t){case"day":r.setDate(e.getDate()+1);break;case"week":r.setDate(e.getDate()+7);break;case"month":r.setMonth(e.getMonth()+1);break;case"year":r.setFullYear(e.getFullYear()+1);break}return r.getTime()}function J(e,t){return e>=-90&&e<=90&&t>=-180&&t<=180}function c(e){if(Array.isArray(e)&&e.length===0)return O({items:[],length:0});let t=Array.isArray(e)?e:Array.from(e);return O({items:t,length:t.length})}function O(collection){function calculateFuzzyScore(e,t){let r=0,n=-1;for(let l of e){let i=t.indexOf(l,n+1);if(i===-1)return 0;r+=1/(i-n),n=i}return r}return{...collection,all(){return[...collection.items]},average(e){return this.avg(e)},collapse(){return c(collection.items.flat())},combine(e){let t={};return collection.items.forEach((r,n)=>{t[String(r)]=e[n]}),c([t])},contains(e,t){if(arguments.length===1){if(e===void 0)return!1;return collection.items.includes(e)}return collection.items.some((r)=>r[e]===t)},containsOneItem(){return collection.length===1},containsAll(e,t){if(arguments.length===1)return e.every((n)=>n===void 0?collection.items.includes(void 0):collection.items.includes(n));let r=e;return(t||[]).every((n)=>collection.items.some((l)=>l[r]===n))},countBy(e){let t=new Map;for(let r of collection.items){let n=typeof e==="function"?e(r):r[e];t.set(n,(t.get(n)||0)+1)}return t},diffAssoc(e){let t=Array.isArray(e)?e:e.items;return c(collection.items.filter((r,n)=>t[n]===void 0||JSON.stringify(r)!==JSON.stringify(t[n])))},diffKeys(e){return c(collection.items.filter((t)=>!e.some((r)=>Object.keys(t).every((n)=>(n in r)))))},diffUsing(e,t){return c(collection.items.filter((r)=>!e.some((n)=>t(r,n)===0)))},doesntContain(e,t){if(arguments.length===1)return!collection.items.includes(e);return!collection.items.some((r)=>r[e]===t)},duplicates(e){let t=new Map,r=collection.items;return r.forEach((n)=>{let l=e?n[e]:n;t.set(l,(t.get(l)||0)+1)}),c(r.filter((n)=>{let l=e?n[e]:n;return t.get(l)>1}))},each(e){return collection.items.forEach(e),this},eachSpread(e){return collection.items.forEach((t)=>{e(...Array.isArray(t)?t:[t])}),this},except(...e){return c(collection.items.map((t)=>{let r={...t};return e.forEach((n)=>delete r[n]),r}))},firstOrFail(){let e=this.first();if(!e)throw new Error("Item not found.");return e},firstWhere(e,t){return collection.items.find((r)=>r[e]===t)},flatten(e=1/0){let t=(r,n)=>{return n>0?r.reduce((l,i)=>l.concat(Array.isArray(i)?t(i,n-1):i),[]):r.slice()};return c(t(collection.items,e))},flip(){if(this.items.length===0)return c([]);let e={};function t(r){if(typeof r!=="object"||r===null)return!1;return Object.values(r).every((n)=>typeof n==="string"||typeof n==="number")}return this.items.forEach((r)=>{if(t(r))Object.entries(r).forEach(([n,l])=>{e[l]=n})}),c([e])},forget(e){return c(collection.items.map((t)=>{let r={...t};return delete r[e],r}))},get(e,t){let r=collection.items[0];return r?r[e]!==void 0?r[e]:t:t},has(e){return collection.items.some((t)=>(e in t))},keyBy(e){return new Map(collection.items.map((t)=>[t[e],t]))},macro(e,t){Object.defineProperty(this,e,{value(...r){return t.apply(this,r)},enumerable:!1,configurable:!0,writable:!0})},make(e){return c(e)},mapInto(e){return c(collection.items.map((t)=>Object.assign(new e,t)))},mapToDictionary(e){let t=new Map;return collection.items.forEach((r)=>{let[n,l]=e(r);t.set(n,l)}),t},mapWithKeys(e){let t=new Map;return collection.items.forEach((r)=>{let[n,l]=e(r);t.set(n,l)}),t},merge(e){let t=Array.isArray(e)?e:e.items;return c([...collection.items,...t])},mergeRecursive(e){function t(l,i){if(i===void 0||i===null)return l;if(Array.isArray(i))return[...i];if(typeof i!=="object")return i;let o=Array.isArray(l)?[...l]:{...l};for(let s of Object.keys(i)){let a=i[s];if(Array.isArray(a))o[s]=[...a];else if(a&&typeof a==="object")o[s]=s in o?t(o[s],a):{...a};else o[s]=a}return o}let r=Array.isArray(e)?e:e.items,n=collection.items.map((l,i)=>{return i<r.length?t(l,r[i]):{...l}});return c(n)},only(...e){return this.map((t)=>{let r={};return e.forEach((n)=>{if(t&&typeof t==="object"&&n in t){let l=n;r[l]=t[l]}}),r})},pad(e,t){let r=collection.items.map((l)=>l),n=Math.abs(e);while(r.length<n)e>0?r.push(t):r.unshift(t);return c(r)},pop(){return collection.items.pop()},prepend(e){let t=[e,...collection.items.map((r)=>r)];return c(t)},pull(e){let t=collection.items[0];return t?t[e]:void 0},push(e){let t=[...collection.items.map((r)=>r),e];return c(t)},put(e,t){return c(collection.items.map((r)=>({...r,[e]:t})))},random(e){let t=[...collection.items];if(typeof e==="undefined"){let n=Math.floor(Math.random()*t.length);return c([t[n]])}let r=t.sort(()=>Math.random()-0.5);return c(r.slice(0,e))},reject(e){return this.filter((t)=>!e(t))},replace(e){return c(e)},replaceRecursive(e){function t(r,n){if(!n||typeof n!=="object")return n;if(Array.isArray(n))return n.map((i,o)=>t(Array.isArray(r)?r[o]:{},i));let l={};for(let i in n)l[i]=t(r?.[i],n[i]);return l}return c(t(collection.items,e))},reverse(){return c([...collection.items].reverse())},shift(){if(collection.length===0)return;let e=collection.items[0];return collection.items.splice(0,1),e},shuffle(){return c([...collection.items].sort(()=>Math.random()-0.5))},skipUntil(e){let t=typeof e==="function"?e:(n)=>n===e,r=collection.items.findIndex(t);return c(r===-1?[]:collection.items.slice(r))},skipWhile(e){let t=typeof e==="function"?e:(n)=>n===e,r=0;while(r<collection.items.length&&t(collection.items[r]))r++;return c(collection.items.slice(r))},slice(e,t){return c(t===void 0?collection.items.slice(e):collection.items.slice(e,e+t))},sole(){if(collection.length!==1)throw new Error("Collection does not contain exactly one item.");return collection.items[0]},sortDesc(){return this.sort((e,t)=>{if(e<t)return 1;if(e>t)return-1;return 0})},sortKeys(){return c(collection.items.map((e)=>{let t={};return Object.keys(e).sort().forEach((r)=>{t[r]=e[r]}),t}))},sortKeysDesc(){return c(collection.items.map((e)=>{let t={};return Object.keys(e).sort((r,n)=>n.localeCompare(r)).forEach((r)=>{t[r]=e[r]}),t}))},splice(e,t,...r){let n=[...collection.items];if(e>n.length)return c(n);if(t===void 0)n.splice(e);else n.splice(e,t,...r);return c(n)},split(e){let t=[],r=Math.ceil(collection.length/e);for(let n=0;n<collection.length;n+=r)t.push(collection.items.slice(n,n+r));return c(t)},takeUntil(e){let t=typeof e==="function"?e:(n)=>n===e,r=collection.items.findIndex(t);return r===-1?c(collection.items):c(collection.items.slice(0,r))},takeWhile(e){let t=typeof e==="function"?e:(n)=>n===e,r=0;while(r<collection.items.length&&t(collection.items[r]))r++;return c(collection.items.slice(0,r))},times(e,t){let r=[];for(let n=0;n<e;n++)r.push(t(n));return c(r)},undot(){let e={};return collection.items.forEach((t)=>{Object.entries(t).forEach(([r,n])=>{r.split(".").reduce((l,i,o,s)=>{if(o===s.length-1)l[i]=n;else l[i]=l[i]||{};return l[i]},e)})}),c([e])},unlessEmpty(e){return this.isNotEmpty()?e(this):this},unlessNotEmpty(e){return this.isEmpty()?e(this):this},unwrap(e){if(e instanceof Object&&"items"in e)return e.toArray();return Array.isArray(e)?e:[e]},whenEmpty(e){return this.isEmpty()?e(this):this},whenNotEmpty(e){return this.isNotEmpty()?e(this):this},wrap(e){if(Array.isArray(e))return c(e);return c([e])},zip(e){return c(collection.items.map((t,r)=>[t,e[r]]))},map(e){return c(collection.items.map(e))},filter(e){return c(collection.items.filter(e))},reduce(e,t){return collection.items.reduce(e,t)},flatMap(e){return c(collection.items.flatMap(e))},first:function(e){let t=collection.items[0];if(arguments.length===0)return t;return t?t[e]:void 0},last:function(e){let t=collection.items[collection.length-1];if(arguments.length===0)return t;return t?t[e]:void 0},nth(e){return collection.items[e]},take(e){return c(collection.items.slice(0,e))},skip(e){return c(collection.items.slice(e))},sum(e){if(collection.length===0)return 0;return collection.items.reduce((t,r)=>{let n=e?Number(r[e]):Number(r);return t+(Number.isNaN(n)?0:n)},0)},avg(e){return collection.length?this.sum(e)/collection.length:0},median(e){if(collection.length===0)return;let t=e?collection.items.map((n)=>Number(n[e])).sort((n,l)=>n-l):collection.items.map((n)=>Number(n)).sort((n,l)=>n-l),r=Math.floor(t.length/2);return t.length%2===0?(t[r-1]+t[r])/2:t[r]},mode(e){if(collection.length===0)return;let t=new Map,r=0,n;for(let l of collection.items){let i=e?l[e]:l,o=(t.get(i)||0)+1;if(t.set(i,o),o>r)r=o,n=l}return n},min(e){if(collection.length===0)return;return collection.items.reduce((t,r)=>{return(e?r[e]:r)<(e?t[e]:t)?r:t})},max(e){if(collection.length===0)return;return collection.items.reduce((t,r)=>{return(e?r[e]:r)>(e?t[e]:t)?r:t})},chunk(e){if(e<1)throw new Error("Chunk size must be greater than 0");let t=[];for(let r=0;r<collection.length;r+=e)t.push(collection.items.slice(r,r+e));return c(t)},groupBy(e){let t=new Map;for(let r of collection.items){let n=typeof e==="function"?e(r):r[e];if(!t.has(n))t.set(n,[]);t.get(n).push(r)}return new Map(Array.from(t.entries()).map(([r,n])=>[r,c(n)]))},partition(e){let t=[],r=[];for(let n of collection.items)if(e(n))t.push(n);else r.push(n);return[c(t),c(r)]},where(e,t){return c(collection.items.filter((r)=>r[e]===t))},whereIn(e,t){let r=new Set(t);return c(collection.items.filter((n)=>r.has(n[e])))},whereNotIn(e,t){let r=new Set(t);return c(collection.items.filter((n)=>!r.has(n[e])))},whereBetween(e,t,r){return c(collection.items.filter((n)=>{let l=n[e];return l>=t&&l<=r}))},whereNotBetween(e,t,r){return c(collection.items.filter((n)=>{let l=n[e];return l<t||l>r}))},unique(e){if(!e)return c([...new Set(collection.items)]);let t=new Set;return c(collection.items.filter((r)=>{let n=r[e];if(t.has(n))return!1;return t.add(n),!0}))},when(e,t){return(typeof e==="function"?e(this):e)?t(this):this},unless(e,t){return(typeof e==="function"?e(this):e)?this:t(this)},sort(e){if(!e){let t=[...collection.items],r=[],n=[],l=[];for(let i of t)if(i===null)r.push(i);else if(i===void 0)n.push(i);else l.push(i);return l.sort((i,o)=>{if(typeof i==="number"&&typeof o==="number")return i-o;return String(i).localeCompare(String(o))}),c([...r,...n,...l])}return c([...collection.items].sort(e))},sortBy(e,t="asc"){let r=[...collection.items];if(r.length===0)return c(r);if(!r.some((n)=>n?.[e]!==void 0&&n[e]!==null))return c(r);return c(r.sort((n,l)=>{let i=n?.[e],o=l?.[e];if(i===void 0||i===null)return t==="asc"?-1:1;if(o===void 0||o===null)return t==="asc"?1:-1;if(typeof i==="number"&&typeof o==="number")return t==="asc"?i-o:o-i;let s=String(i).localeCompare(String(o));return t==="asc"?s:-s}))},sortByDesc(e){return this.sortBy(e,"desc")},pluck(e){return c(collection.items.map((t)=>t[e]))},values(){return c([...collection.items])},keys(e){return c(Array.from(new Set(collection.items.map((t)=>t[e]))))},intersect(e){let t=new Set(Array.isArray(e)?e:e.items);return c(collection.items.filter((r)=>t.has(r)))},union(e){let t=Array.isArray(e)?e:e.items;return c([...new Set([...collection.items,...t])])},tap(e){return e(this),this},pipe(e){return e(this)},isEmpty(){return collection.length===0},isNotEmpty(){return collection.length>0},count(){return collection.length},toArray(){return[...collection.items]},toMap(e){return new Map(collection.items.map((t)=>[t[e],t]))},toSet(){return new Set(collection.items)},product(e){if(collection.length===0)return 0;return collection.items.reduce((t,r)=>{let n=e?Number(r[e]):Number(r);return t*(Number.isNaN(n)?1:n)},1)},standardDeviation(e){if(collection.length<=1)return{population:0,sample:0};let t=this.avg(e),r=collection.items.map((i)=>{let o=(e?Number(i[e]):Number(i))-t;return o*o}),n=r.reduce((i,o)=>i+o,0)/collection.length,l=r.reduce((i,o)=>i+o,0)/(collection.length-1);return{population:Math.sqrt(n),sample:Math.sqrt(l)}},percentile(e,t){if(e<0||e>100||collection.length===0)return;let r=t?collection.items.map((l)=>Number(l[t])).sort((l,i)=>l-i):collection.items.map((l)=>Number(l)).sort((l,i)=>l-i),n=Math.ceil(e/100*r.length)-1;return r[n]},variance(e){return this.standardDeviation(e).population**2},frequency(e){let t=new Map;for(let r of collection.items){let n=e?r[e]:r;t.set(n,(t.get(n)||0)+1)}return t},whereNull(e){return c(collection.items.filter((t)=>t[e]==null))},whereNotNull(e){return c(collection.items.filter((t)=>t[e]!=null))},whereLike(e,t){let r=new RegExp(t.replace(/%/g,".*"),"i");return c(collection.items.filter((n)=>r.test(String(n[e]))))},whereRegex(e,t){return c(collection.items.filter((r)=>t.test(String(r[e]))))},whereInstanceOf(e){return c(collection.items.filter((t)=>t instanceof e))},async mapAsync(e){let t=await Promise.all(collection.items.map((r,n)=>e(r,n)));return c(t)},async filterAsync(e){let t=await Promise.all(collection.items.map(async(r,n)=>({item:r,keep:await e(r,n)})));return c(t.filter(({keep:r})=>r).map(({item:r})=>r))},async reduceAsync(e,t){let r=t;for(let n of collection.items)r=await e(r,n);return r},async everyAsync(e){return(await Promise.all(collection.items.map((t,r)=>e(t,r)))).every((t)=>t)},async someAsync(e){return(await Promise.all(collection.items.map((t,r)=>e(t,r)))).some((t)=>t)},paginate(e,t=1){let r=collection.length,n=Math.ceil(r/e),l=Math.min(Math.max(t,1),n);return{data:this.forPage(l,e),total:r,perPage:e,currentPage:l,lastPage:n,hasMorePages:l<n}},forPage(e,t){if(e<1||t<=0)return c([]);let r=(e-1)*t;if(r>=collection.items.length)return c([]);return c(collection.items.slice(r,r+t))},async*cursor(e){let t=0;while(t<collection.length)yield c(collection.items.slice(t,t+e)),t+=e},symmetricDiff(e){let t=Array.isArray(e)?e:e.items,r=new Set(t),n=new Set(collection.items),l=new Set;return collection.items.forEach((i)=>{if(!r.has(i))l.add(i)}),t.forEach((i)=>{if(!n.has(i))l.add(i)}),c([...l])},cartesianProduct(e){let t=Array.isArray(e)?e:e.items,r=[];for(let n of collection.items)for(let l of t)r.push([n,l]);return c(r)},groupByMultiple(...e){let t=new Map;for(let r of collection.items){let n=e.map((l)=>String(r[l])).join("::");if(!t.has(n))t.set(n,[]);t.get(n).push(r)}return new Map(Array.from(t.entries()).map(([r,n])=>[r,c(n)]))},describe(e){let t=new Map;t.set("count",this.count()),t.set("mean",this.avg(e)),t.set("min",Number(this.min(e))),t.set("max",Number(this.max(e))),t.set("sum",this.sum(e));let r=this.standardDeviation(e);t.set("stdDev",r.population),t.set("variance",this.variance(e));let n=this.percentile(25,e),l=this.percentile(75,e);if(n!==void 0&&l!==void 0)t.set("q1",n),t.set("q3",l),t.set("iqr",l-n);return t},debug(){return console.log({items:collection.items,length:collection.length,memory:k.memoryUsage()}),this},dump(){console.log(collection.items)},dd(){this.dump(),k.exit(1)},timeSeries({dateField:e,valueField:t,interval:r="day",fillGaps:n=!0}){let l=collection.items.map((m)=>{let f=m[e],p=m[t],g=f instanceof Date?f:new Date(String(f)),b=typeof p==="number"?p:Number(p);return{date:g,value:b}}).filter((m)=>!Number.isNaN(m.date.getTime())).sort((m,f)=>m.date.getTime()-f.date.getTime());if(!n||l.length===0)return c(l);let i=Math.min(...l.map((m)=>m.date.getTime())),o=Math.max(...l.map((m)=>m.date.getTime())),s=i,a=[],u=o+1;while(s<u){let m=new Date(s),f=l.find((p)=>Z(p.date,m));a.push({date:new Date(m),value:f?f.value:0}),s=W(m,r)}return c(a)},movingAverage({window:e,centered:t=!1}){if(collection.length===0)return c([]);if(e<1)throw new Error("Invalid window size");if(e>collection.length)throw new Error("Invalid window size");if(e===collection.length){let i=collection.items.reduce((o,s)=>Number(o)+Number(s),0)/e;return c([i])}let r=collection.items.map((i)=>Number(i)),n=[],l=t?Math.floor(e/2):0;for(let i=0;i<=r.length-e;i++){let o=r.slice(i,i+e).reduce((s,a)=>s+a,0);n[i+l]=o/e}if(t){let i=Math.floor(e/2);for(let s=0;s<i;s++){let a=r.slice(0,e);n[s]=a.reduce((u,m)=>u+m,0)/a.length}let o=Math.ceil(e/2)-1;for(let s=0;s<o;s++){let a=r.length-o+s,u=r.slice(-e);n[a]=u.reduce((m,f)=>m+f,0)/u.length}}return c(n)},async validate(e){let t=new Map,r=Object.entries(e);for(let[n,l]of r){if(!l||!Array.isArray(l))continue;for(let i of collection.items){let o=i[n],s=[];for(let a of l)try{if(!await a(o))s.push(`Validation failed for ${String(n)}`)}catch(u){s.push(`Validation error for ${String(n)}: ${u instanceof Error?u.message:"Unknown error"}`)}if(s.length>0)t.set(String(n),s)}}return{isValid:t.size===0,errors:t}},validateSync(e){let t=new Map,r=Object.entries(e);for(let[n,l]of r){if(!l||!Array.isArray(l))continue;for(let i of collection.items){let o=i[n],s=[];for(let a of l)try{let u=a(o);if(u instanceof Promise)throw new TypeError("Async validation rules are not supported in validateSync");if(!u)s.push(`Validation failed for ${String(n)}`)}catch(u){s.push(`Validation error for ${String(n)}: ${u instanceof Error?u.message:"Unknown error"}`)}if(s.length>0)t.set(String(n),s)}}return{isValid:t.size===0,errors:t}},stream(){let e=0;return new ReadableStream({pull:(t)=>{if(e<collection.length)t.enqueue(collection.items[e++]);else t.close()}})},async fromStream(e){let t=[],r=e.getReader();try{while(!0){let{done:n,value:l}=await r.read();if(n)break;t.push(l)}}finally{r.releaseLock()}return c(t)},fuzzyMatch(e,t,r=0.7){function n(i,o){let s=[];for(let a=0;a<=i.length;a++)s[a]=[a];for(let a=0;a<=o.length;a++)s[0][a]=a;for(let a=1;a<=i.length;a++)for(let u=1;u<=o.length;u++){let m=i[a-1]===o[u-1]?0:1;s[a][u]=Math.min(s[a-1][u]+1,s[a][u-1]+1,s[a-1][u-1]+m)}return s[i.length][o.length]}function l(i,o){let s=Math.max(i.length,o.length);return s===0?1:1-n(i,o)/s}return c(collection.items.filter((i)=>l(String(i[e]),t)>=r))},metrics(){let e={count:this.count(),nullCount:0,uniqueCount:this.unique().count(),heapUsed:0,heapTotal:0},t=k.memoryUsage();if(e.heapUsed=t.heapUsed,e.heapTotal=t.heapTotal,collection.length>0){let r=collection.items[0],n=Object.keys(r);e.fieldCount=n.length;let l=new Map;for(let i of n){let o=collection.items.filter((s)=>s[i]===null).length;l.set(String(i),o),e.nullCount+=o}e.nullFieldsDistribution=l}return e},async profile(){let e=k.hrtime(),t=k.memoryUsage().heapUsed;await Promise.resolve([...collection.items]);let[r,n]=k.hrtime(e),l=k.memoryUsage().heapUsed;return{time:r*1000+n/1e6,memory:l-t}},transform(e){return c(collection.items.map((t)=>{let r={},n=Object.entries(e);for(let[l,i]of n)r[l]=i(t);return r}))},kmeans({k:e,maxIterations:t=100,distanceMetric:r="euclidean"}){if(collection.length===0)return x(c([]));if(e<=0||e>collection.length)throw new Error("Invalid k value");let n=collection.items.map((u)=>{return Object.values(u).filter((m)=>typeof m==="number")});if(n.some((u)=>u.length===0))throw new Error("No numeric values found in data");let l=n.slice(0,e).map((u)=>[...u]),i=Array.from({length:n.length}).fill(0),o=0,s=!0;while(s&&o<t){s=!1,n.forEach((u,m)=>{let f=l.map((p,g)=>({index:g,distance:r==="euclidean"?Math.sqrt(u.reduce((b,v,A)=>b+(v-p[A])**2,0)):u.reduce((b,v,A)=>b+Math.abs(v-p[A]),0)})).reduce((p,g)=>g.distance<p.distance?g:p);if(i[m]!==f.index)s=!0,i[m]=f.index});for(let u=0;u<e;u++){let m=n.filter((f,p)=>i[p]===u);if(m.length>0)l[u]=m[0].map((f,p)=>m.reduce((g,b)=>g+b[p],0)/m.length)}o++}let a=collection.items.map((u,m)=>({cluster:i[m],data:u}));return x(c(a))},linearRegression(e,t){if(collection.length<=t.length)throw new Error("Insufficient data points for regression");try{let r=function(h,y){return h.reduce((N,w,$)=>N+w*y[$],0)},n=function(h){return h[0].map((y,N)=>h.map((w)=>w[N]))},l=collection.items.map((h)=>Number(h[e])),i=collection.items.map((h)=>[1,...t.map((y)=>Number(h[y]))]),o=n(i),s=o.map((h)=>i[0].map((y,N)=>r(h,i.map((w)=>w[N])))),a=o.map((h)=>r(h,l)),u=0.0000000001;for(let h=0;h<s.length;h++)s[h][h]+=u;let m=s.length,f=s.map((h,y)=>[...h,a[y]]);for(let h=0;h<m;h++){let y=h;for(let w=h+1;w<m;w++)if(Math.abs(f[w][h])>Math.abs(f[y][h]))y=w;if(y!==h)[f[h],f[y]]=[f[y],f[h]];let N=f[h][h];if(Math.abs(N)<0.0000000001)throw new Error("Matrix is nearly singular");for(let w=h;w<=m;w++)f[h][w]/=N;for(let w=0;w<m;w++)if(w!==h){let $=f[w][h];for(let _=h;_<=m;_++)f[w][_]-=$*f[h][_]}}let p=f.map((h)=>h[m]),g=i.map((h)=>r(h,p)),b=l.reduce((h,y)=>h+y,0)/l.length,v=l.reduce((h,y)=>h+(y-b)**2,0),A=g.reduce((h,y,N)=>h+(l[N]-y)**2,0),d=v===0?0:Math.min(1,Math.max(0,1-A/v)),M=l.map((h,y)=>h-g[y]);return{coefficients:p,rSquared:Number.isFinite(d)?d:0,predictions:g,residuals:M}}catch(r){let n=collection.length,l=collection.items.map((o)=>Number(o[e])),i=l.reduce((o,s)=>o+s,0)/n;return{coefficients:Array.from({length:t.length+1},()=>0),rSquared:0,predictions:Array.from({length:n},()=>i),residuals:l.map((o)=>o-i)}}},async parallel(e,t={}){let{chunks:r=navigator.hardwareConcurrency||4,maxConcurrency:n=r}=t,l=Math.ceil(collection.length/r),i=this.chunk(l),o=0,s=[],a=[];for(let u=0;u<i.count();u++){let m=i.nth(u);if(!m)continue;while(o>=n)await Promise.race(s);o++;let f,p=(async()=>{try{let g=await e(c(m));if(Array.isArray(g))a.push(...g);else if(g&&typeof g.toArray==="function")a.push(...g.toArray());else a.push(g)}finally{o--,f?.()}})();f=()=>{let g=s.indexOf(p);if(g>-1)s.splice(g,1)},s.push(p)}return await Promise.all(s),c(a)},index(e){let t=new Map;for(let r of e){let n=new Map;for(let l of collection.items){let i=l[r];if(!n.has(i))n.set(i,[]);n.get(i).push(l)}t.set(r,n)}return this.__indexes=t,this},explain(){let e=[],t=this;while(t.__previous)e.unshift(t.__operation),t=t.__previous;return e.map((r,n)=>`${n+1}. ${r}`).join(`
2
- `)},async benchmark(){let e={},t={},r={},n=["filter","map","reduce","sort"];for(let l of n){let i=performance.now(),o=k.memoryUsage().heapUsed;switch(l){case"filter":this.filter(()=>!0),r[l]="O(n)";break;case"map":this.map((s)=>s),r[l]="O(n)";break;case"reduce":this.reduce((s)=>s,null),r[l]="O(n)";break;case"sort":this.sort(),r[l]="O(n log n)";break}e[l]=performance.now()-i,t[l]=k.memoryUsage().heapUsed-o}return{timing:e,memory:t,complexity:r}},lazy(){async function*e(t){for(let r of t)yield r}return S(e(collection.items))},mapToGroups(e){let t=new Map;for(let r of collection.items){let[n,l]=e(r);if(!t.has(n))t.set(n,[]);t.get(n).push(l)}return new Map(Array.from(t.entries()).map(([r,n])=>[r,c(n)]))},mapSpread(e){return c(collection.items.map((t)=>e(...Array.isArray(t)?t:[t])))},mapUntil(e,t){let r=[];for(let n=0;n<collection.items.length;n++){let l=e(collection.items[n],n);if(t(l))break;r.push(l)}return c(r)},pivot(e,t){return new Map(collection.items.map((r)=>[r[e],r[t]]))},join(e){return collection.items.join(e)},implode(e,t=""){return collection.items.map((r)=>String(r[e])).join(t)},lower(){return c(collection.items.map((e)=>String(e).toLowerCase()))},upper(){return c(collection.items.map((e)=>String(e).toUpperCase()))},slug(){return c(collection.items.map((e)=>String(e).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"")))},power(){let e=[[]];for(let t of collection.items){let r=e.length;for(let n=0;n<r;n++)e.push([...e[n],t])}return c(e.map((t)=>c(t)))},correlate(e,t){let r=collection.items.map((a)=>Number(a[e])),n=collection.items.map((a)=>Number(a[t])),l=r.reduce((a,u)=>a+u,0)/r.length,i=n.reduce((a,u)=>a+u,0)/n.length,o=r.reduce((a,u)=>a+(u-l)**2,0),s=n.reduce((a,u)=>a+(u-i)**2,0);return r.reduce((a,u,m)=>a+(r[m]-l)*(n[m]-i),0)/Math.sqrt(o*s)},outliers(e,t=2){let r=collection.items.map((i)=>Number(i[e])),n=r.reduce((i,o)=>i+o,0)/r.length,l=Math.sqrt(r.reduce((i,o)=>i+(o-n)**2,0)/r.length);return c(collection.items.filter((i)=>Math.abs((Number(i[e])-n)/l)>t))},cast(e){return c(collection.items.map((t)=>new e(t)))},zscore(e){if(e===void 0){let l=this.items,i=l.reduce((s,a)=>s+a,0)/l.length,o=Math.sqrt(l.reduce((s,a)=>s+(a-i)**2,0)/l.length);return c(l.map((s)=>(s-i)/o))}let t=collection.items.map((l)=>Number(l[e])),r=t.reduce((l,i)=>l+i,0)/t.length,n=Math.sqrt(t.reduce((l,i)=>l+(i-r)**2,0)/t.length);return c(t.map((l)=>(l-r)/n))},kurtosis(e){let t;if(e===void 0)t=this.items;else t=collection.items.map((l)=>Number(l[e]));let r=t.reduce((l,i)=>l+i,0)/t.length,n=Math.sqrt(t.reduce((l,i)=>l+(i-r)**2,0)/t.length);return t.reduce((l,i)=>l+(i-r)**4,0)/t.length/n**4-3},skewness(e){let t;if(e===void 0)t=this.items;else t=collection.items.map((l)=>Number(l[e]));let r=t.reduce((l,i)=>l+i,0)/t.length,n=Math.sqrt(t.reduce((l,i)=>l+(i-r)**2,0)/t.length);return t.reduce((l,i)=>l+(i-r)**3,0)/t.length/n**3},covariance(e,t){let r=collection.items.map((o)=>Number(o[e])),n=collection.items.map((o)=>Number(o[t])),l=r.reduce((o,s)=>o+s,0)/r.length,i=n.reduce((o,s)=>o+s,0)/n.length;return r.reduce((o,s,a)=>o+(r[a]-l)*(n[a]-i),0)/r.length},entropy(e){let t;if(e===void 0)t=this.items;else t=collection.items.map((n)=>n[e]);let r=new Map;for(let n of t)r.set(n,(r.get(n)||0)+1);return-Array.from(r.values()).map((n)=>n/t.length).reduce((n,l)=>n+l*Math.log2(l),0)},mapOption(e){return c(collection.items.map(e).filter((t)=>t!=null))},zipWith(e,t){let r=Math.min(collection.length,e.count()),n=[];for(let l=0;l<r;l++)n.push(t(collection.items[l],e.toArray()[l]));return c(n)},scan(e,t){let r=[],n=t;for(let l of collection.items)n=e(n,l),r.push(n);return c(r)},unfold(e,t){let r=[],n=t,l=e(n);while(l!==null){let[i,o]=l;r.push(i),n=o,l=e(n)}return c(r)},as(e){return c(collection.items.map((t)=>{let r=new e,n=Object.keys(r),l=t;return n.forEach((i)=>{if(i in l)r[i]=l[i]}),r}))},pick(...e){return c(collection.items.map((t)=>{let r={};for(let n of e)r[n]=t[n];return r}))},omit(...e){let t=new Set(e);return c(collection.items.map((r)=>{let n={};for(let l of Object.keys(r))if(!t.has(l))n[l]=r[l];return n}))},search(e,t,r={}){let{fuzzy:n=!1,weights:l={}}=r,i=e.toLowerCase();return c(collection.items.map((o)=>{let s=0;for(let a of t){let u=String(o[a]).toLowerCase(),m=l[a]||1;if(n)s+=calculateFuzzyScore(i,u)*m;else s+=u.includes(i)?m:0}return{...o,score:s}})).filter((o)=>o.score>0).sort((o,s)=>s.score-o.score)},aggregate(e,t){let r=this.groupBy(e),n=new Map;for(let[l,i]of r.entries()){let o={};for(let s of t)switch(s){case"sum":o.sum=i.sum();break;case"avg":o.avg=i.avg();break;case"min":o.min=Number(i.min());break;case"max":o.max=Number(i.max());break;case"count":o.count=i.count();break}n.set(l,o)}return n},pivotTable(e,t,r,n){let l=new Map,i=new Set(collection.items.map((s)=>s[e])),o=new Set(collection.items.map((s)=>s[t]));for(let s of i){let a=new Map;for(let u of o){let m=this.filter((p)=>p[e]===s&&p[t]===u),f;switch(n){case"sum":f=m.sum(r);break;case"avg":f=m.avg(r);break;case"count":f=m.count();break}a.set(u,f)}l.set(s,a)}return l},toSQL(e){if(collection.length===0)return"";let t=Object.keys(collection.items[0]),r=collection.items.map((n)=>`(${t.map((l)=>JSON.stringify(n[l])).join(", ")})`).join(`,
3
- `);return`INSERT INTO ${e} (${t.join(", ")})
4
- VALUES
5
- ${r};`},toGraphQL(e){if(collection.length===0)return`query {
6
- ${e}s {
7
- []
8
- }
9
- }`;let t=Object.keys(collection.items[0]);return`query {
10
- ${e}s {
11
- nodes {
12
- ${collection.items.map((r)=>` ${e} {
13
- ${t.map((n)=>` ${n}: ${JSON.stringify(r[n])}`).join(`
14
- `)}
15
- }`).join(`
16
- `)}
17
- }
18
- }
19
- }`},toElastic(e){return{index:e,body:collection.items.flatMap((t)=>[{index:{_index:e}},t])}},toPandas(){if(collection.length===0)return"pd.DataFrame()";return`pd.DataFrame([
20
- ${collection.items.map((e)=>JSON.stringify(e)).join(`,
21
- `)}
22
- ])`},playground(){console.log("Collection Playground:",{items:collection.items,length:collection.length,operations:Object.keys(this)})},fft(){if(!collection.items.every((t)=>typeof t==="number"))throw new Error("FFT can only be performed on number collections");function e(t){let r=t.length;if(r<=1)return[[t[0],0]];let n=e(t.filter((o,s)=>s%2===0)),l=e(t.filter((o,s)=>s%2===1)),i=new Array(r);for(let o=0;o<r/2;o++){let s=-2*Math.PI*o/r,a=[Math.cos(s)*l[o][0]-Math.sin(s)*l[o][1],Math.sin(s)*l[o][0]+Math.cos(s)*l[o][1]];i[o]=[n[o][0]+a[0],n[o][1]+a[1]],i[o+r/2]=[n[o][0]-a[0],n[o][1]-a[1]]}return i}return c(e(collection.items))},interpolate(e){if(e<2)throw new Error("Points must be greater than 1");if(this.count()===1){let l=Number(this.first());return c(new Array(e).fill(l))}let t=this.toArray(),r=[],n=(t.length-1)/(e-1);for(let l=0;l<e;l++){let i=l*n,o=Math.floor(i),s=Math.min(Math.ceil(i),t.length-1),a=t[o],u=t[s];r.push(a+(u-a)*(i-o))}return c(r)},convolve(e){if(e.length===0)throw new Error("Kernel must not be empty");if(this.count()===0)throw new Error("Signal must not be empty");let t=this.toArray(),r=t.length,n=e.length,l=[];for(let i=0;i<r+n-1;i++){let o=0;for(let s=Math.max(0,i-n+1);s<=Math.min(r-1,i);s++)o+=t[s]*e[i-s];l.push(o)}return c(l)},differentiate(){if(this.count()<=1)return c([]);let e=this.toArray();return c(e.slice(1).map((t,r)=>Number(t)-Number(e[r])))},integrate(){let e=this.toArray();if(e.length===0)return c([0]);let t=[0],r=0;for(let n of e)r+=n,t.push(r);return c(t)},geoDistance(e,t,r="km"){function n(l,i,o,s){if(!J(l,i)||!J(o,s))throw new Error("Invalid coordinates");let a=r==="km"?6371:3959,u=(o-l)*Math.PI/180,m=(s-i)*Math.PI/180,f=l*Math.PI/180,p=o*Math.PI/180,g=Math.sin(u/2)*Math.sin(u/2)+Math.cos(f)*Math.cos(p)*Math.sin(m/2)*Math.sin(m/2),b=2*Math.atan2(Math.sqrt(g),Math.sqrt(1-g));return a*b}return c(collection.items.map((l)=>{let i=l[e];if(!i||!Array.isArray(i)||i.length!==2)throw new Error("Invalid coordinates");return{...l,distance:n(i[0],i[1],t[0],t[1])}}))},money(e,t="USD"){let r=new Intl.NumberFormat("en-US",{style:"currency",currency:t});return c(collection.items.map((n)=>({...n,formatted:r.format(Number(n[e]))})))},dateTime(e,t="en-US"){return c(collection.items.map((r)=>({...r,formatted:new Date(r[e]).toLocaleString(t)})))},configure(e){if(e.locale)Intl.NumberFormat.prototype.format=new Intl.NumberFormat(e.locale).format;if(e.timezone)Intl.DateTimeFormat.prototype.format=new Intl.DateTimeFormat(void 0,{timeZone:e.timezone}).format},trend(e){let t=this.timeSeries(e),r=t.count(),n=Array.from({length:r},(f,p)=>p),l=t.pluck("value").toArray(),i=n.reduce((f,p)=>f+p,0),o=l.reduce((f,p)=>f+p,0),s=n.reduce((f,p,g)=>f+p*l[g],0),a=n.reduce((f,p)=>f+p*p,0),u=(r*s-i*o)/(r*a-i*i),m=(o-u*i)/r;return{slope:u,intercept:m}},seasonality(e){let t=this.timeSeries(e),r=new Map,n=t.groupBy((l)=>{let i=l.date;switch(e.interval){case"month":return i.getMonth().toString();case"week":return i.getDay().toString();default:return i.getDate().toString()}});for(let[l,i]of n)r.set(String(l),i.avg("value"));return r},forecast(e){let t=this.trend({dateField:"",valueField:""}),r=this.last();if(!r)return c([]);let n=Array.from({length:e},(l,i)=>{let o={...r},s=t.slope*(this.count()+i)+t.intercept,a=o;if(typeof a.value!=="undefined")a.value=s;return a});return c(n)},async assertValid(e){let t=await this.validate(e);if(!t.isValid)throw new Error(`Validation failed: ${JSON.stringify(Array.from(t.errors.entries()))}`)},sanitize(e){return this.map((t)=>{let r={...t};for(let[n,l]of Object.entries(e))r[n]=l(t[n]);return r})},query(sql,params=[]){let lowerSQL=sql.toLowerCase(),result=this;if(lowerSQL.includes("where")){let whereClause=sql.split("where")[1].trim(),paramIndex=0;result=this.filter((item)=>{let parsedClause=whereClause.replace(/\$\{(\w+)\}/g,(e,t)=>{return JSON.stringify(item[t])}).replace(/\?/g,()=>{let e=params[paramIndex];return paramIndex++,JSON.stringify(e)});return eval(parsedClause)})}return result},having(e,t,r){let n={">":(l,i)=>l>i,"<":(l,i)=>l<i,">=":(l,i)=>l>=i,"<=":(l,i)=>l<=i,"=":(l,i)=>l===i,"!=":(l,i)=>l!==i};return this.filter((l)=>n[t](l[e],r))},crossJoin(e){let t=[];for(let r of this.items)for(let n of e.items)t.push({...r,...n});return c(t)},leftJoin(e,t,r){return this.map((n)=>{let l=e.items.find((i)=>{let o=n[t],s=i[r];return o===s});return{...n,...l||{}}})},batch(e){return this.cursor(e)},toJSON(e={}){let{pretty:t=!1,exclude:r=[],include:n}=e,l=this.items.map((i)=>{let o={},s=n||Object.keys(i);for(let a of s)if(!r.includes(a))o[a]=i[a];return o});return JSON.stringify(l,null,t?2:void 0)},toCsv(e={}){let{exclude:t=[],include:r}=e,n=this.toArray();if(n.length===0)return"";let l=(r||Object.keys(n[0])).filter((o)=>!t.includes(o)),i=n.map((o)=>l.map((s)=>JSON.stringify(o[s])).join(","));return[l.join(","),...i].join(`
23
- `)},toXml(e={}){let{exclude:t=[],include:r}=e,n=this.toArray(),l="items",i="item";function o(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}return`<?xml version="1.0" encoding="UTF-8"?>
24
- <items>
25
- ${n.map((s)=>{return`<item>
26
- ${(r||Object.keys(s)).filter((a)=>!t.includes(a)).map((a)=>` <${a}>${o(String(s[a]))}</${a}>`).join(`
27
- `)}
28
- </item>`}).join(`
29
- `)}
30
- </items>`},parse(e,t){switch(t){case"json":return c(JSON.parse(e));case"csv":{let r=e.trim().split(`
31
- `),n=r[0].split(","),l=r.slice(1).map((i)=>{let o=i.split(","),s={};return n.forEach((a,u)=>{s[a]=o[u]}),s});return c(l)}case"xml":throw new Error("XML parsing not implemented");default:throw new Error(`Unsupported format: ${t}`)}},cache(e=60000){let t=new Map,r=JSON.stringify(this.items),n=Date.now(),l=t.get(r);if(l&&l.expiry>n)return c(l.data);return t.set(r,{data:[...this.items],expiry:n+e}),this},memoize(e){let t=new Map,r=this.items.map((n)=>{let l=n[e];if(!t.has(l))t.set(l,n);return t.get(l)});return c(r)},async prefetch(){let e=await Promise.all(this.items.map(async(t)=>{if(t instanceof Promise)return await t;return await Promise.resolve(t)}));return c(e)},sentiment(){let e=new Set(["good","great","awesome","excellent","happy","love"]),t=new Set(["bad","terrible","awful","horrible","sad","hate"]),r=[new Set(["great","awesome"])];return this.map((n)=>{let l=n.toLowerCase().replace(/[.,!?]*/g,"").split(/\s+/).filter((s)=>s.length>0),i=0,o=new Set;return l.forEach((s)=>{if(e.has(s)){let a=!1;if(r.forEach((u,m)=>{if(u.has(s)&&o.has(m))a=!0}),!a)i++,r.forEach((u,m)=>{if(u.has(s))o.add(m)})}if(t.has(s))i--}),{score:i,comparative:i/l.length}})},wordFrequency(){let e=new Map;return this.items.forEach((t)=>{t.toLowerCase().split(/\s+/).forEach((r)=>{e.set(r,(e.get(r)||0)+1)})}),e},ngrams(e){return c(this.items.flatMap((t)=>{let r=t.split(/\s+/),n=[];for(let l=0;l<=r.length-e;l++)n.push(r.slice(l,l+e).join(" "));return n}))},instrument(e){let t=new Map;t.set("count",this.count()),t.set("operations",0),t.set("timeStart",Date.now());let r=new Proxy(this,{get(n,l){if(typeof n[l]==="function")t.set("operations",(t.get("operations")||0)+1);return n[l]}});return e(t),r},optimize(){let e=this.cache();if(this.count()>1000){let t=this.first();if(t){let r=Object.keys(t);e.index(r)}}return e},removeOutliers(e,t=2){let r=this.pluck(e).toArray(),n=r.reduce((i,o)=>Number(i)+Number(o),0)/r.length,l=Math.sqrt(r.reduce((i,o)=>i+(Number(o)-n)**2,0)/r.length);return this.filter((i)=>{let o=Number(i[e]);return Math.abs((o-n)/l)<=t})},impute(e,t){let r=this.pluck(e).toArray(),n;switch(t){case"mean":{n=r.reduce((l,i)=>Number(l)+Number(i),0)/r.length;break}case"median":{let l=[...r].sort((o,s)=>Number(o)-Number(s)),i=Math.floor(l.length/2);n=l[i];break}case"mode":{let l=new Map,i=0,o=r[0];for(let s of r){let a=(l.get(s)||0)+1;if(l.set(s,a),a>i)i=a,o=s}n=o;break}}return this.map((l)=>({...l,[e]:l[e]??n}))},normalize(e,t){let r=this.pluck(e).toArray().map(Number);if(t==="minmax"){let i=Math.min(...r),o=Math.max(...r)-i;return this.map((s)=>({...s,[e]:o!==0?(Number(s[e])-i)/o:0}))}let n=r.reduce((i,o)=>i+o,0)/r.length,l=Math.sqrt(r.reduce((i,o)=>i+(o-n)**2,0)/r.length);return this.map((i)=>({...i,[e]:l!==0?(Number(i[e])-n)/l:0}))},knn(e,t,r){function n(i,o){return Math.sqrt(Array.from(r).reduce((s,a)=>{let u=o[a],m=i[a];if(u===void 0)return s;let f=Number(m),p=Number(u);if(Number.isNaN(f)||Number.isNaN(p))return s;let g=f-p;return s+g*g},0))}let l=collection.items.map((i)=>({item:i,distance:n(i,e)})).sort((i,o)=>i.distance-o.distance).slice(0,Math.min(t,collection.items.length)).map((i)=>i.item);return c(l)},naiveBayes(e,t){let r=new Set(this.pluck(t).toArray()),n=new Map,l=new Map;for(let i of r){let o=this.where(t,i);n.set(i,o.count()/this.count()),l.set(i,new Map);for(let s of e){let a=new Map,u=new Set(o.pluck(s).toArray());for(let m of u){let f=o.where(s,m).count();a.set(m,f/o.count())}l.get(i).set(s,a)}}return(i)=>{let o=-1/0,s=Array.from(r)[0];for(let a of r){let u=Math.log(n.get(a)||0);for(let m of e){let f=i[m],p=l.get(a)?.get(m)?.get(f)||0.0001;u+=Math.log(p)}if(u>o)o=u,s=a}return s}},detectAnomalies(e){let{method:t="zscore",threshold:r=2,features:n=[]}=e;switch(t){case"zscore":{let l=n.length>0?n:Object.keys(this.first()||{});return this.filter((i)=>{for(let o of l){let s=this.pluck(o).toArray().map(Number),a=s.reduce((m,f)=>m+f,0)/s.length,u=Math.sqrt(s.reduce((m,f)=>m+(f-a)**2,0)/s.length);if(Math.abs((Number(i[o])-a)/u)>r)return!0}return!1})}case"iqr":{let l=n.length>0?n:Object.keys(this.first()||{});return this.filter((i)=>{for(let o of l){let s=this.pluck(o).toArray().map(Number).sort((p,g)=>p-g),a=s[Math.floor(s.length*0.25)],u=s[Math.floor(s.length*0.75)],m=u-a,f=Number(i[o]);if(f<a-r*m||f>u+r*m)return!0}return!1})}case"isolationForest":{let l=function(a,u,m){if(m>=o||a.length<=1)return m;let f=a.map((d)=>Number(d[u])),p=Math.min(...f),g=Math.max(...f),b=p+Math.random()*(g-p),v=a.filter((d)=>Number(d[u])<b),A=a.filter((d)=>Number(d[u])>=b);return Math.max(l(v,u,m+1),l(A,u,m+1))},i=Math.min(256,this.count()),o=Math.ceil(Math.log2(i)),s=n.length>0?n:Object.keys(this.first()||{});return this.filter((a)=>{return s.reduce((u,m)=>{let f=l([a],m,0);return u+f},0)/s.length<r})}}}}}function x(e){let t=e.pluck.bind(e),r=e;function n(l){let i=t(l);if(l==="cluster"){let o=i;return{values:()=>o.toArray(),toArray:()=>o.toArray(),*[Symbol.iterator](){yield*o.toArray()}}}if(l==="data"){let o=i;return{values:()=>o.toArray(),toArray:()=>o.toArray(),forEach:(s)=>{o.toArray().forEach(s)},avg:(s)=>{let a=o.toArray().map((u)=>Number(u[s])).filter((u)=>!Number.isNaN(u));return a.reduce((u,m)=>u+m,0)/a.length},filter:(s)=>{let a=o.toArray().filter(s);return D(c(a))}}}return i}return r.pluck=n,r}function D(e){return{values:()=>e.toArray(),toArray:()=>e.toArray(),forEach:(t)=>{e.toArray().forEach(t)},avg:(t)=>{let r=e.toArray().map((n)=>Number(n[t])).filter((n)=>!Number.isNaN(n));return r.reduce((n,l)=>n+l,0)/r.length},filter:(t)=>{let r=e.toArray().filter(t);return D(c(r))}}}export{c as collect};
1
+ export{e as collect};
@@ -0,0 +1 @@
1
+ export { collect } from 'ts-collect';
package/package.json CHANGED
@@ -1,10 +1,12 @@
1
1
  {
2
2
  "name": "@stacksjs/collections",
3
3
  "type": "module",
4
- "version": "0.70.23",
4
+ "version": "0.70.26",
5
5
  "description": "The Stacks collections.",
6
6
  "author": "Chris Breuer",
7
- "contributors": ["Chris Breuer <chris@stacksjs.org>"],
7
+ "contributors": [
8
+ "Chris Breuer <chris@stacksjs.com>"
9
+ ],
8
10
  "license": "MIT",
9
11
  "funding": "https://github.com/sponsors/chrisbbreuer",
10
12
  "homepage": "https://github.com/stacksjs/stacks/tree/main/storage/framework/core/collections#readme",
@@ -27,15 +29,21 @@
27
29
  "sideEffects": false,
28
30
  "exports": {
29
31
  ".": {
32
+ "types": "./dist/index.d.ts",
33
+ "bun": "./src/index.ts",
30
34
  "import": "./dist/index.js"
31
35
  },
32
36
  "./*": {
37
+ "bun": "./src/*",
33
38
  "import": "./dist/*"
34
39
  }
35
40
  },
36
41
  "module": "dist/index.js",
37
42
  "types": "dist/index.d.ts",
38
- "files": ["README.md", "dist"],
43
+ "files": [
44
+ "README.md",
45
+ "dist"
46
+ ],
39
47
  "scripts": {
40
48
  "build": "bun build.ts",
41
49
  "typecheck": "bun tsc --noEmit",
@@ -43,7 +51,7 @@
43
51
  "prepublishOnly": "bun run build"
44
52
  },
45
53
  "devDependencies": {
46
- "@stacksjs/development": "0.70.22",
54
+ "better-dx": "^0.2.12",
47
55
  "ts-collect": "^0.4.0"
48
56
  }
49
57
  }
package/dist/index.d.ts DELETED
@@ -1 +0,0 @@
1
- export { collect } from 'ts-collect'