@stacksjs/arrays 0.75.445 → 0.75.447
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/math.js +1 -1
- package/dist/transform.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -69,3 +69,15 @@ returns an empty array; sample counts must be nonnegative safe integers.
|
|
|
69
69
|
uses the same safe midpoint. `min()` and `max()` iterate rather than spreading arguments,
|
|
70
70
|
so large browser data sets do not exceed the engine's function argument limit. Empty
|
|
71
71
|
statistical inputs retain their existing errors.
|
|
72
|
+
|
|
73
|
+
## Numeric and selection contracts
|
|
74
|
+
|
|
75
|
+
Population variance, standard deviation, covariance and z-scores use centered,
|
|
76
|
+
scaled arithmetic for finite observations. Standard deviation can remain finite
|
|
77
|
+
when variance exceeds the number range. Unrepresentable final results and nonfinite
|
|
78
|
+
inputs keep their IEEE number behavior; these helpers do not round for display.
|
|
79
|
+
|
|
80
|
+
`minBy`/`maxBy` accept infinite endpoints, ignore NaN candidates, and retain the
|
|
81
|
+
first tied element. `take`, `takeLast`, `drop` and `dropLast` truncate fractional
|
|
82
|
+
counts toward zero and clamp negatives/NaN to zero; Infinity means the whole input.
|
|
83
|
+
`sortBy` evaluates every selector once per element and preserves stable ties.
|
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");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)))}
|
|
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 centered=centeredValues(array);if(centered)return scaledProduct(centered.variance,centered.scale,centered.scale);const mean=average(array);return average(array.map((num)=>(num-mean)**2))}export function standardDeviation(array){const centered=centeredValues(array);if(centered)return Math.sqrt(centered.variance)*centered.scale;return Math.sqrt(variance(array))}export function zScore(array,num){const centered=centeredValues(array);if(centered)return(normalizedDifference(num,centered.anchor,centered.scale)-centered.mean)/Math.sqrt(centered.variance);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 exact=finiteCovariance(array1,array2);if(exact!==void 0)return exact;const mean1=average(array1),mean2=average(array2);return average(array1.map((num1,i)=>(num1-mean1)*(array2[i]-mean2)))}function finiteCovariance(first,second){if(first.length===0)throw Error("Cannot compute average of an empty array");const view=new DataView(new ArrayBuffer(8));let sumFirst=0n,sumSecond=0n,sumProducts=0n;for(let index=0;index<first.length;index++){const x=first[index],y=second[index];if(!Number.isFinite(x)||!Number.isFinite(y))return;const[a,shiftA]=binaryCoefficient(x,view),[b,shiftB]=binaryCoefficient(y,view);sumFirst+=a<<shiftA;sumSecond+=b<<shiftB;sumProducts+=a*b<<shiftA+shiftB}const count=BigInt(first.length),numerator=count*sumProducts-sumFirst*sumSecond;return binaryRatio(numerator,count*count)}function binaryCoefficient(value,view){view.setFloat64(0,value);const bits=view.getBigUint64(0),exponent=bits>>52n&0x7ffn;let coefficient=bits&0xfffffffffffffn;if(exponent!==0n)coefficient|=1n<<52n;if(bits>>63n)coefficient=-coefficient;return[coefficient,exponent===0n?0n:exponent-1n]}function binaryRatio(numerator,denominator){const negative=numerator<0n,magnitude=negative?-numerator:numerator,integer=magnitude/denominator,shift=Math.max(1074,integer.toString(2).length-53),divisor=denominator<<BigInt(shift);let coefficient=magnitude/divisor;const remainder=magnitude%divisor;if(remainder*2n>divisor||remainder*2n===divisor&&(coefficient&1n)!==0n)coefficient++;const result=Number(coefficient)*2**(shift-2148);return negative?-result:result}function centeredValues(array){if(array.length===0)throw Error("Cannot compute average of an empty array");let scale=0;for(const value of array){if(!Number.isFinite(value))return;scale=Math.max(scale,Math.abs(value))}if(scale===0)scale=1;const anchor=array[0],differences=array.map((value)=>normalizedDifference(value,anchor,scale)),mean=average(differences),deviations=differences.map((value)=>value-mean);return{scale,anchor,mean,variance:average(deviations.map((value)=>value*value))}}function normalizedDifference(value,anchor,scale){const difference=value-anchor;return Number.isFinite(difference)?difference/scale:value/scale-anchor/scale}function scaledProduct(value,first,second){const factors=[value,first,second].sort((a,b)=>Math.abs(a)-Math.abs(b));return factors[0]*factors[2]*factors[1]}
|
package/dist/transform.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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
|
|
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 array.slice(0,normalizedCount(count))}export function takeLast(array,count){count=normalizedCount(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 array.slice(normalizedCount(count))}export function dropLast(array,count){count=normalizedCount(count);return count<=0?array.slice():array.slice(0,Math.max(0,array.length-count))}function normalizedCount(count){return Math.max(0,Math.trunc(count)||0)}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});if(normalized.length===0)return array.slice();return array.map((value)=>({value,keys:normalized.map(({by})=>by(value))})).sort((left,right)=>{for(let index=0;index<normalized.length;index++){const{order}=normalized[index],comparison=compareSelected(left.keys[index],right.keys[index]);if(comparison!==0)return order==="desc"?-comparison:comparison}return 0}).map((entry)=>entry.value)}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 found=!1,best,bestValue=Number.NEGATIVE_INFINITY;for(const[index,item]of array.entries()){const candidate=value(item,index);if(!Number.isNaN(candidate)&&(!found||candidate>bestValue)){found=!0;bestValue=candidate;best=item}}return best}export function minBy(array,value){let found=!1,best,bestValue=Number.POSITIVE_INFINITY;for(const[index,item]of array.entries()){const candidate=value(item,index);if(!Number.isNaN(candidate)&&(!found||candidate<bestValue)){found=!0;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}
|