Last active
August 29, 2015 14:05
-
-
Save zz85/edc3a675b369e3a72910 to your computer and use it in GitHub Desktop.
Simple Histogram Stats
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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