Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Array.avg Array.stdDev

  • Loading branch information...
commit a2b62096929a59808b0300142bb1beaa246120d8 1 parent c04ee7b
@erh erh authored
Showing with 25 additions and 0 deletions.
  1. +8 −0 jstests/array3.js
  2. +17 −0 shell/utils.js
View
8 jstests/array3.js
@@ -0,0 +1,8 @@
+
+assert.eq( 5 , Array.sum( [ 1 , 4 ] ), "A" )
+assert.eq( 2.5 , Array.avg( [ 1 , 4 ] ), "B" )
+
+arr = [ 2 , 4 , 4 , 4 , 5 , 5 , 7 , 9 ]
+assert.eq( 5 , Array.avg( arr ) , "C" )
+assert.eq( 2 , Array.stdDev( arr ) , "D" )
+
View
17 shell/utils.js
@@ -255,6 +255,23 @@ Array.sum = function( arr ){
return s;
}
+Array.avg = function( arr ){
+ if ( arr.length == 0 )
+ return null;
+ return Array.sum( arr ) / arr.length;
+}
+
+Array.stdDev = function( arr ){
+ var avg = Array.avg( arr );
+ var sum = 0;
+
+ for ( var i=0; i<arr.length; i++ ){
+ sum += Math.pow( arr[i] - avg , 2 );
+ }
+
+ return Math.sqrt( sum / arr.length );
+}
+
if ( ! ObjectId.prototype )
ObjectId.prototype = {}
Please sign in to comment.
Something went wrong with that request. Please try again.