3 Copyright (c) 2014 The Chromium Authors. All rights reserved.
4 Use of this source code is governed by a BSD-style license that can be
5 found in the LICENSE file.
7 <link rel="import" href="/tvcm/range.html">
11 tvcm.exportTo('tvcm', function() {
13 function identity(d) {
17 function Statistics() {
20 Statistics.sum = function(ary, opt_func, opt_this) {
21 var func = opt_func || identity;
23 for (var i = 0; i < ary.length; i++)
24 ret += func.call(opt_this, ary[i], i);
28 Statistics.mean = function(ary, opt_func, opt_this) {
29 return Statistics.sum(ary, opt_func, opt_this) / ary.length;
32 Statistics.variance = function(ary, opt_func, opt_this) {
33 var func = opt_func || identity;
34 var mean = Statistics.mean(ary, func, opt_this);
35 var sumOfSuaredDistances = Statistics.sum(
38 var v = func.call(this, d, i) - mean;
42 return sumOfSuaredDistances / (ary.length - 1);
45 Statistics.variance = function(ary, opt_func, opt_this) {
47 Statistics.variance(ary, opt_func, opt_this));
50 Statistics.max = function(ary, opt_func, opt_this) {
51 var func = opt_func || identity;
53 for (var i = 0; i < ary.length; i++)
54 ret = Math.max(ret, func.call(opt_this, ary[i], i));
58 Statistics.min = function(ary, opt_func, opt_this) {
59 var func = opt_func || identity;
61 for (var i = 0; i < ary.length; i++)
62 ret = Math.min(ret, func.call(opt_this, ary[i], i));
66 Statistics.range = function(ary, opt_func, opt_this) {
67 var func = opt_func || identity;
68 var ret = new tvcm.Range();
69 for (var i = 0; i < ary.length; i++)
70 ret.addValue(func.call(opt_this, ary[i], i));
74 Statistics.percentile = function(ary, percent, opt_func, opt_this) {
75 if (!(percent >= 0 && percent <= 1))
76 throw new Error('percent must be [0,1]');
78 var func = opt_func || identity;
79 var tmp = new Array(ary.length);
80 for (var i = 0; i < ary.length; i++)
81 tmp[i] = func.call(opt_this, ary[i], i);
83 var idx = Math.floor((ary.length - 1) * percent);
88 Statistics: Statistics