@stacksjs/arrays 0.75.439 → 0.75.445
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 +12 -0
- package/dist/helpers.d.ts +2 -2
- package/dist/helpers.js +1 -1
- package/dist/math.js +1 -1
- package/dist/series.d.ts +1 -0
- package/dist/series.js +1 -1
- package/dist/transform.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -57,3 +57,15 @@ For casual chit-chat with others using this package:
|
|
|
57
57
|
The MIT License (MIT). Please see [LICENSE](https://github.com/stacksjs/stacks/tree/main/LICENSE.md) for more information.
|
|
58
58
|
|
|
59
59
|
Made with 💙
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
## Boundary behavior
|
|
63
|
+
|
|
64
|
+
`at()` and `last()` return `T | undefined` for arrays that may be empty or indexes that
|
|
65
|
+
may be out of range. Handle the missing value before dereferencing it. `sample([], n)`
|
|
66
|
+
returns an empty array; sample counts must be nonnegative safe integers.
|
|
67
|
+
|
|
68
|
+
`average()` scales finite inputs when their intermediate sum overflows, and `median()`
|
|
69
|
+
uses the same safe midpoint. `min()` and `max()` iterate rather than spreading arguments,
|
|
70
|
+
so large browser data sets do not exceed the engine's function argument limit. Empty
|
|
71
|
+
statistical inputs retain their existing errors.
|
package/dist/helpers.d.ts
CHANGED
|
@@ -93,7 +93,7 @@ export declare function uniqueBy<T>(array: readonly T[], equalFn: (a: T, b: T) =
|
|
|
93
93
|
* ```
|
|
94
94
|
*/
|
|
95
95
|
export declare function last(array: readonly []): undefined;
|
|
96
|
-
export declare function last<T>(array: readonly T[]): T;
|
|
96
|
+
export declare function last<T>(array: readonly T[]): T | undefined;
|
|
97
97
|
/**
|
|
98
98
|
* Remove an item from Array.
|
|
99
99
|
*
|
|
@@ -123,7 +123,7 @@ export declare function remove<T>(array: T[], value: T): boolean;
|
|
|
123
123
|
* ```
|
|
124
124
|
*/
|
|
125
125
|
export declare function at(array: readonly [], index: number): undefined;
|
|
126
|
-
export declare function at<T>(array: readonly T[], index: number): T;
|
|
126
|
+
export declare function at<T>(array: readonly T[], index: number): T | undefined;
|
|
127
127
|
/**
|
|
128
128
|
* Move an item from one index to another
|
|
129
129
|
* @param array
|
package/dist/helpers.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export function toArray(array){array=array??[];return Array.isArray(array)?array:[array]}export function flatten(array){return toArray(array).reduce((acc,val)=>acc.concat(Array.isArray(val)?flatten(val):val),[])}export function mergeArrayable(...args){return args.flatMap((i)=>toArray(i))}export function partition(array,...filters){const result=Array.from({length:filters.length+1}).fill(null).map(()=>[]);array.forEach((e,idx,arr)=>{let i=0;for(const filter of filters){if(filter(e,idx,arr)){result[i].push(e);return}i+=1}result[i].push(e)});return result}export function uniq(array){return Array.from(new Set(array))}export function unique(array){return uniq(array)}export function uniqueBy(array,equalFn){return array.reduce((acc,cur)=>{if(acc.findIndex((item)=>equalFn(cur,item))===-1)acc.push(cur);return acc},[])}export function last(array){return at(array,-1)}export function remove(array,value){if(!array)return!1;const index=array.indexOf(value);if(index>=0){array.splice(index,1);return!0}return!1}export function at(array,index){const len=array.length;if(!len)return;if(index<0)index+=len;return array[index]}export function move(array,from,to){const len=array.length;if(!Number.isSafeInteger(from)||!Number.isSafeInteger(to))throw RangeError("move indices must be safe integers");if(!len)return array;if(from<0)from+=len;if(to<0)to+=len;if(from<0||from>=len||to<0||to>len)throw RangeError("move index is out of bounds");const item=array.splice(from,1)[0];array.splice(to,0,item);return array}function clamp(n,min,max){return Math.min(max,Math.max(min,n))}export function clampArrayRange(arr,n){return clamp(n,0,arr.length-1)}export function sample(arr,count){return Array.from({length:count},()=>arr[Math.floor(Math.random()*arr.length)])}export function shuffle(array){for(let i=array.length-1;i>0;i--){const j=Math.floor(Math.random()*(i+1));[array[i],array[j]]=[array[j],array[i]]}return array}
|
|
1
|
+
export function toArray(array){array=array??[];return Array.isArray(array)?array:[array]}export function flatten(array){return toArray(array).reduce((acc,val)=>acc.concat(Array.isArray(val)?flatten(val):val),[])}export function mergeArrayable(...args){return args.flatMap((i)=>toArray(i))}export function partition(array,...filters){const result=Array.from({length:filters.length+1}).fill(null).map(()=>[]);array.forEach((e,idx,arr)=>{let i=0;for(const filter of filters){if(filter(e,idx,arr)){result[i].push(e);return}i+=1}result[i].push(e)});return result}export function uniq(array){return Array.from(new Set(array))}export function unique(array){return uniq(array)}export function uniqueBy(array,equalFn){return array.reduce((acc,cur)=>{if(acc.findIndex((item)=>equalFn(cur,item))===-1)acc.push(cur);return acc},[])}export function last(array){return at(array,-1)}export function remove(array,value){if(!array)return!1;const index=array.indexOf(value);if(index>=0){array.splice(index,1);return!0}return!1}export function at(array,index){const len=array.length;if(!len)return;if(index<0)index+=len;return array[index]}export function move(array,from,to){const len=array.length;if(!Number.isSafeInteger(from)||!Number.isSafeInteger(to))throw RangeError("move indices must be safe integers");if(!len)return array;if(from<0)from+=len;if(to<0)to+=len;if(from<0||from>=len||to<0||to>len)throw RangeError("move index is out of bounds");const item=array.splice(from,1)[0];array.splice(to,0,item);return array}function clamp(n,min,max){return Math.min(max,Math.max(min,n))}export function clampArrayRange(arr,n){return clamp(n,0,arr.length-1)}export function sample(arr,count){if(!Number.isSafeInteger(count)||count<0)throw RangeError("sample count must be a non-negative safe integer");if(arr.length===0)return[];return Array.from({length:count},()=>arr[Math.floor(Math.random()*arr.length)])}export function shuffle(array){for(let i=array.length-1;i>0;i--){const j=Math.floor(Math.random()*(i+1));[array[i],array[j]]=[array[j],array[i]]}return array}
|
package/dist/math.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export function average(arr){if(arr.length===0)throw Error("Cannot compute average of an empty array");
|
|
1
|
+
export function average(arr){if(arr.length===0)throw Error("Cannot compute average of an empty array");const total=sum(arr);if(Number.isFinite(total)||arr.some((value)=>!Number.isFinite(value)))return total/arr.length;const scale=arr.reduce((largest,value)=>Math.max(largest,Math.abs(value)),0);return arr.reduce((acc,value)=>acc+value/scale,0)/arr.length*scale}export function avg(arr){return average(arr)}export function median(arr){if(arr.length===0)throw Error("Cannot compute median of an empty array");const sorted=[...arr].sort((a,b)=>a-b),mid=Math.floor(sorted.length/2);let medianValue;if(sorted.length%2!==0)medianValue=sorted[mid];else medianValue=average([sorted[mid],sorted[mid-1]]);return medianValue}export function mode(arr){if(arr.length===0)throw Error("Cannot compute mode of an empty array");const counts=new Map;for(const v of arr)counts.set(v,(counts.get(v)||0)+1);let maxCount=0,result=arr[0];for(const[value,count]of counts)if(count>maxCount){maxCount=count;result=value}return result}export function sum(array){return array.reduce((acc,cur)=>acc+cur,0)}export function product(array){let acc=1;for(const cur of array){acc*=cur;if(Number.isFinite(acc)&&Math.abs(acc)>Number.MAX_SAFE_INTEGER)throw RangeError(`[arrays.product] Result exceeds Number.MAX_SAFE_INTEGER (${Number.MAX_SAFE_INTEGER}); use BigInt for large products.`)}return acc}export function min(array){if(array.length===0)throw Error("Cannot compute min of an empty array");let result=1/0;for(const value of array)result=Math.min(result,value);return result}export function max(array){if(array.length===0)throw Error("Cannot compute max of an empty array");let result=-1/0;for(const value of array)result=Math.max(result,value);return result}export function range(array){return max(array)-min(array)}export function variance(array){const mean=average(array);return average(array.map((num)=>(num-mean)**2))}export function standardDeviation(array){return Math.sqrt(variance(array))}export function zScore(array,num){return(num-average(array))/standardDeviation(array)}export function percentile(array,num){if(array.length===0)throw Error("Cannot compute a percentile of an empty array");if(!Number.isFinite(num)||num<0||num>100)throw RangeError(`A percentile is between 0 and 100, got ${num}`);const sorted=[...array].sort((a,b)=>a-b),index=num/100*(sorted.length-1),lower=Math.floor(index),upper=Math.ceil(index),weight=index-lower;if(upper===lower)return sorted[index]??0;return(1-weight)*(sorted[lower]??0)+weight*(sorted[upper]??0)}export function interquartileRange(array){if(array.length===0)throw Error("Cannot compute the interquartile range of an empty array");if(array.length===1)return 0;const sorted=[...array].sort((a,b)=>a-b),q1=median(sorted.slice(0,Math.floor(sorted.length/2)));return median(sorted.slice(Math.ceil(sorted.length/2)))-q1}export function covariance(array1,array2){if(array1.length!==array2.length)throw Error("Arrays must have the same length");const mean1=average(array1),mean2=average(array2);return average(array1.map((num1,i)=>(num1-mean1)*(array2[i]-mean2)))}
|
package/dist/series.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { average } from './math';
|
|
1
2
|
/** Reject absent and nonnumeric values without turning null, false or blanks into zero. */
|
|
2
3
|
export declare function finiteNumeric(value: unknown): number | null;
|
|
3
4
|
/** Prefer a direct source per field; a missing field can fall back to another source. */
|
package/dist/series.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export function finiteNumeric(value){if(typeof value!=="number"&&typeof value!=="string")return null;if(typeof value==="string"&&!value.trim())return null;const number=Number(value);return Number.isFinite(number)?number:null}function updateInstant(value){const instant=value?Date.parse(value):NaN;return Number.isFinite(instant)?instant:-1/0}export function mergeDailySeries(rows,priority=[]){const rank=(source)=>{const at=priority.indexOf(source);return at<0?priority.length:at},sorted=[...rows].sort((a,b)=>rank(a.source)-rank(b.source)||updateInstant(b.updatedAt)-updateInstant(a.updatedAt)||a.source.localeCompare(b.source)),days=new Map;for(const row of sorted){if(!/^\d{4}-\d{2}-\d{2}$/.test(row.day))continue;const parsed=new Date(`${row.day}T00:00:00Z`);if(!Number.isFinite(parsed.getTime())||parsed.toISOString().slice(0,10)!==row.day)continue;const point=days.get(row.day)||{date:row.day,values:{},sources:{}};for(const[key,raw]of Object.entries(row.values)){if(Object.hasOwn(point.values,key))continue;const value=finiteNumeric(raw);if(value===null)continue;Object.defineProperty(point.values,key,{value,enumerable:!0,configurable:!0,writable:!0});Object.defineProperty(point.sources,key,{value:row.source,enumerable:!0,configurable:!0,writable:!0})}if(Object.keys(point.values).length)days.set(row.day,point)}return[...days.values()].sort((a,b)=>a.date.localeCompare(b.date))}export function summarizeSeries(points){const valid=points.filter((point)=>Number.isFinite(point.value)).sort((a,b)=>a.date.localeCompare(b.date));let
|
|
1
|
+
import{average}from"./math";export function finiteNumeric(value){if(typeof value!=="number"&&typeof value!=="string")return null;if(typeof value==="string"&&!value.trim())return null;const number=Number(value);return Number.isFinite(number)?number:null}function updateInstant(value){const instant=value?Date.parse(value):NaN;return Number.isFinite(instant)?instant:-1/0}export function mergeDailySeries(rows,priority=[]){const rank=(source)=>{const at=priority.indexOf(source);return at<0?priority.length:at},sorted=[...rows].sort((a,b)=>rank(a.source)-rank(b.source)||updateInstant(b.updatedAt)-updateInstant(a.updatedAt)||a.source.localeCompare(b.source)),days=new Map;for(const row of sorted){if(!/^\d{4}-\d{2}-\d{2}$/.test(row.day))continue;const parsed=new Date(`${row.day}T00:00:00Z`);if(!Number.isFinite(parsed.getTime())||parsed.toISOString().slice(0,10)!==row.day)continue;const point=days.get(row.day)||{date:row.day,values:{},sources:{}};for(const[key,raw]of Object.entries(row.values)){if(Object.hasOwn(point.values,key))continue;const value=finiteNumeric(raw);if(value===null)continue;Object.defineProperty(point.values,key,{value,enumerable:!0,configurable:!0,writable:!0});Object.defineProperty(point.sources,key,{value:row.source,enumerable:!0,configurable:!0,writable:!0})}if(Object.keys(point.values).length)days.set(row.day,point)}return[...days.values()].sort((a,b)=>a.date.localeCompare(b.date))}export function summarizeSeries(points){const valid=points.filter((point)=>Number.isFinite(point.value)).sort((a,b)=>a.date.localeCompare(b.date));let lowest=1/0,highest=-1/0;for(const point of valid){lowest=Math.min(lowest,point.value);highest=Math.max(highest,point.value)}return{count:valid.length,latest:valid.at(-1)??null,average:valid.length?average(valid.map((point)=>point.value)):null,lowest:valid.length?lowest:null,highest:valid.length?highest:null}}
|
package/dist/transform.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export function chunk(array,size){if(!Number.isInteger(size)||size<1)throw TypeError(`chunk: size must be a positive integer, got ${size}`);const chunks=[];for(let index=0;index<array.length;index+=size)chunks.push(array.slice(index,index+size));return chunks}export function compact(array){return array.filter((value)=>value!==null&&value!==void 0)}export function first(array){return array[0]}export function tail(array){return array.slice(1)}export function take(array,count){return count<=0?[]:array.slice(0,count)}export function takeLast(array,count){return count<=0?[]:array.slice(Math.max(0,array.length-count))}export function takeWhile(array,predicate){const result=[];for(const[index,value]of array.entries()){if(!predicate(value,index))break;result.push(value)}return result}export function takeLastWhile(array,predicate){for(let index=array.length-1;index>=0;index--)if(!predicate(array[index],index))return array.slice(index+1);return array.slice()}export function drop(array,count){return count<=0?array.slice():array.slice(count)}export function dropLast(array,count){return count<=0?array.slice():array.slice(0,Math.max(0,array.length-count))}export function dropWhile(array,predicate){for(const[index,value]of array.entries())if(!predicate(value,index))return array.slice(index);return[]}export function dropLastWhile(array,predicate){for(let index=array.length-1;index>=0;index--)if(!predicate(array[index],index))return array.slice(0,index+1);return[]}function defineValue(target,key,value){Object.defineProperty(target,key,{value,enumerable:!0,configurable:!0,writable:!0})}export function groupBy(array,key){const groups={};for(const[index,value]of array.entries()){const group=key(value,index);if(group===void 0)continue;if(!Object.hasOwn(groups,group))defineValue(groups,group,[]);groups[group].push(value)}return groups}export function keyBy(array,key){const indexed={};for(const[index,value]of array.entries()){const at=key(value,index);if(at!==void 0)defineValue(indexed,at,value)}return indexed}export function countBy(array,key){const counts={};for(const[index,value]of array.entries()){const at=key(value,index);if(at!==void 0)defineValue(counts,at,(Object.hasOwn(counts,at)?counts[at]:0)+1)}return counts}function compareSelected(a,b){if(a instanceof Date&&b instanceof Date)return a.getTime()-b.getTime();if(typeof a==="string"&&typeof b==="string")return a<b?-1:a>b?1:0;if(typeof a==="boolean"&&typeof b==="boolean")return Number(a)-Number(b);if(typeof a==="bigint"&&typeof b==="bigint")return a<b?-1:a>b?1:0;return Number(a)-Number(b)}export function sortBy(array,...selectors){const normalized=selectors.map((selector)=>typeof selector==="function"?{by:selector,order:"asc"}:{order:"asc",...selector});return array.slice().sort((left,right)=>{for(const{by,order}of normalized){const comparison=compareSelected(by(left),by(right));if(comparison!==0)return order==="desc"?-comparison:comparison}return 0})}export function sumBy(array,value){let total=0;for(const[index,item]of array.entries())total+=value(item,index);return total}export function meanBy(array,value){return array.length===0?void 0:
|
|
1
|
+
import{average}from"./math";export function chunk(array,size){if(!Number.isInteger(size)||size<1)throw TypeError(`chunk: size must be a positive integer, got ${size}`);const chunks=[];for(let index=0;index<array.length;index+=size)chunks.push(array.slice(index,index+size));return chunks}export function compact(array){return array.filter((value)=>value!==null&&value!==void 0)}export function first(array){return array[0]}export function tail(array){return array.slice(1)}export function take(array,count){return count<=0?[]:array.slice(0,count)}export function takeLast(array,count){return count<=0?[]:array.slice(Math.max(0,array.length-count))}export function takeWhile(array,predicate){const result=[];for(const[index,value]of array.entries()){if(!predicate(value,index))break;result.push(value)}return result}export function takeLastWhile(array,predicate){for(let index=array.length-1;index>=0;index--)if(!predicate(array[index],index))return array.slice(index+1);return array.slice()}export function drop(array,count){return count<=0?array.slice():array.slice(count)}export function dropLast(array,count){return count<=0?array.slice():array.slice(0,Math.max(0,array.length-count))}export function dropWhile(array,predicate){for(const[index,value]of array.entries())if(!predicate(value,index))return array.slice(index);return[]}export function dropLastWhile(array,predicate){for(let index=array.length-1;index>=0;index--)if(!predicate(array[index],index))return array.slice(0,index+1);return[]}function defineValue(target,key,value){Object.defineProperty(target,key,{value,enumerable:!0,configurable:!0,writable:!0})}export function groupBy(array,key){const groups={};for(const[index,value]of array.entries()){const group=key(value,index);if(group===void 0)continue;if(!Object.hasOwn(groups,group))defineValue(groups,group,[]);groups[group].push(value)}return groups}export function keyBy(array,key){const indexed={};for(const[index,value]of array.entries()){const at=key(value,index);if(at!==void 0)defineValue(indexed,at,value)}return indexed}export function countBy(array,key){const counts={};for(const[index,value]of array.entries()){const at=key(value,index);if(at!==void 0)defineValue(counts,at,(Object.hasOwn(counts,at)?counts[at]:0)+1)}return counts}function compareSelected(a,b){if(a instanceof Date&&b instanceof Date)return a.getTime()-b.getTime();if(typeof a==="string"&&typeof b==="string")return a<b?-1:a>b?1:0;if(typeof a==="boolean"&&typeof b==="boolean")return Number(a)-Number(b);if(typeof a==="bigint"&&typeof b==="bigint")return a<b?-1:a>b?1:0;return Number(a)-Number(b)}export function sortBy(array,...selectors){const normalized=selectors.map((selector)=>typeof selector==="function"?{by:selector,order:"asc"}:{order:"asc",...selector});return array.slice().sort((left,right)=>{for(const{by,order}of normalized){const comparison=compareSelected(by(left),by(right));if(comparison!==0)return order==="desc"?-comparison:comparison}return 0})}export function sumBy(array,value){let total=0;for(const[index,item]of array.entries())total+=value(item,index);return total}export function meanBy(array,value){return array.length===0?void 0:average(Array.from(array,value))}export function maxBy(array,value){let best,bestValue=Number.NEGATIVE_INFINITY;for(const[index,item]of array.entries()){const candidate=value(item,index);if(candidate>bestValue){bestValue=candidate;best=item}}return best}export function minBy(array,value){let best,bestValue=Number.POSITIVE_INFINITY;for(const[index,item]of array.entries()){const candidate=value(item,index);if(candidate<bestValue){bestValue=candidate;best=item}}return best}export function zip(first,second){const length=Math.min(first.length,second.length),pairs=[];for(let index=0;index<length;index++)pairs.push([first[index],second[index]]);return pairs}export function zipWith(first,second,combine){const length=Math.min(first.length,second.length),combined=[];for(let index=0;index<length;index++)combined.push(combine(first[index],second[index],index));return combined}export function unzip(pairs){const first=[],second=[];for(const[a,b]of pairs){first.push(a);second.push(b)}return[first,second]}export function difference(array,other){const exclude=new Set(other);return array.filter((value)=>!exclude.has(value))}export function intersection(array,other){const include=new Set(other),seen=new Set;return array.filter((value)=>{if(!include.has(value)||seen.has(value))return!1;seen.add(value);return!0})}export function union(...arrays){return[...new Set(arrays.flat())]}export function splitAt(array,index){return[array.slice(0,index),array.slice(index)]}export function splitWhen(array,predicate){for(const[index,value]of array.entries())if(predicate(value,index))return[array.slice(0,index),array.slice(index)];return[array.slice(),[]]}export function times(count,create){if(!Number.isInteger(count)||count<0)throw TypeError(`times: count must be a non-negative integer, got ${count}`);const result=Array.from({length:count});for(let index=0;index<count;index++)result[index]=create(index);return result}
|