Skip to content

Instantly share code, notes, and snippets.

@zz85
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zz85/edc3a675b369e3a72910 to your computer and use it in GitHub Desktop.
Save zz85/edc3a675b369e3a72910 to your computer and use it in GitHub Desktop.
Simple Histogram Stats
function Histogram() {
this.reset();
}
Histogram.prototype.reset = function() {
this.counts = [];
this.types = {};
};
Histogram.prototype.add = function(type) {
if (type in this.types) {
this.types[type].count++;
} else {
var counter = {
type: type,
count: 1
};
this.counts.push(counter);
this.types[type] = counter;
}
};
Histogram.prototype.count = function() {
return this.counts.length;
};
Histogram.prototype.array = function() {
return this.counts;
};
function dsc(a, b) {
return b.count - a.count;
}
function asc(b, a) {
return b.count - a.count;
}
Histogram.prototype.sort = function() {
this.counts.sort(dsc);
};
Histogram.prototype.sum = function() {
var counts = this.counts;
var sum = 0, i = 0, il = counts.length;
for (;i<il;i++) {
sum += counts[i].count;
}
return sum;
};
Histogram.prototype.mean = function() {
return this.sum() / this.count();
};
Histogram.prototype.medium = function() {
var mid = this.count() / 2 | 0;
return this.counts[mid];
};
file_types = new Histogram();
file_types.add('js');
file_types.add('sh');
file_types.add('js');
file_types.add('png');
file_types.add('jpg');
file_types.add('js');
file_types.add('js');
file_types.add('html');
file_types.add('html');
file_types.sort();
console.log('count', file_types.count());
console.log('sum', file_types.sum());
console.log('mean', file_types.mean());
console.log('medium', file_types.medium());
console.log(file_types.array());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment