Prep: Summarize ages
Prep algorithm
by bladnman
HTML
<input type=button id="theButton" value="run test" class="runButton">
<div id="log" class="log"></div>
CSS
.runButton {
width: 125px;
margin: 20px;
}
.log {
padding:10px;
margin: 20px;
border: 1px dotted #ccc;
color:#888;
font-face: arial;
font-size:12px;
background: #fbfbfb;
}
JavaScript
/* ************************************ */
function runTest() {
var ages = [3,4,7,8,3,5,2,4,4,2,6,7,8,3,1,3,6,7,8,3,2];
summarize();
summarize(ages);
}
function summarize(data) {
// bail -- INVALID DATA
if (typeof(data) == "undefined") {
log("invalid data offered to summarize: " + data);
return;
}
var ageTotalsHash = {};
for (var i=0; i < data.length; i++) {
var dataVal = data[i];
if (typeof(ageTotalsHash[dataVal]) == "undefined") {
ageTotalsHash[dataVal] = 1;
}
else {
ageTotalsHash[dataVal]++
}
}
var ages = Object.keys(ageTotalsHash);
ages = ages.sort();
for (var k=0; k < ages.length; k++ ){
var thisAge = ages[k];
log(thisAge + " = " + ageTotalsHash[thisAge]);
}
return hash;
}
/* ************************************
_____ ___ __ __ ___ _ _ _____ ___
|_ _| __| \/ | _ \ | /_\_ _| __|
| | | _|| |\/| | _/ |__ / _ \| | | _|
|_| |___|_| |_|_| |____/_/ \_\_| |___|
************************************ */
function log(message, value) {
var outMessage = message;
if (typeof value !== "undefined" && value !== null) {
outMessage += " [" + value + "]";
}
if ($("#log").html() != "") {
$("#log").append("<br>");
}
$("#log").append(outMessage);
if (window.console && console.log) {
console.log(outMessage);
}
}
$("#theButton").live('click', function() {
runTest();
});