forked from Khan/khan-exercises
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stat.js
56 lines (48 loc) · 1.2 KB
/
stat.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
jQuery.extend(KhanUtil, {
sum: function( values ) {
var sum = 0;
$.each(values, function( index, value ) {
sum += value;
});
return sum;
},
mean: function( values ) {
return KhanUtil.sum( values ) / values.length;
},
median: function( values ) {
var sortedInts, median;
sortedInts = KhanUtil.sortNumbers( values );
if ( values.length % 2 === 0 ) {
median = KhanUtil.roundTo( 1,
( sortedInts[(values.length / 2) - 1] + sortedInts[values.length / 2] ) / 2 );
} else {
median = sortedInts[ Math.floor( values.length / 2 ) ];
}
return median;
},
mode: function( values ) {
var numInstances = [];
var modeInstances = -1;
var mode;
for ( var i = 0; i < values.length; i++ ) {
if ( !numInstances[ values[i] ] ) {
numInstances[ values[i] ] = 1;
} else {
numInstances[ values[i] ] += 1;
if ( numInstances[ values[i] ] > modeInstances ) {
modeInstances = numInstances[ values[i] ];
mode = values[i];
}
}
}
// iterate again to check for 'no mode'
for ( var i = 0; i < numInstances.length; i++ ) {
if ( numInstances[i] ) {
if ( i !== mode && numInstances[i] >= modeInstances ) {
return false;
}
}
}
return mode;
}
});