Skip to content

Instantly share code, notes, and snippets.

@solenoid
Created May 11, 2012 20:27
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 solenoid/2662212 to your computer and use it in GitHub Desktop.
Save solenoid/2662212 to your computer and use it in GitHub Desktop.
Example of raw Yieldbot js code
var _ = require('underscore'),
d3 = require('d3');
// This is an example of some functional heavy code used at Yieldbot
// prepare raw data into 20 minute buckets and
// return data along with relevant max info and scale functions
var prep = function (data) {
var total = 0;
var prepared = _.map(_.keys(data), function (hour) {
var buckets = _.reduce(_.keys(data[hour]), function (memo, minute) {
var m = parseInt(minute, 10);
if (m < 20) {
memo[0] += data[hour][minute];
}
if (m >= 20 && m < 40) {
memo[1] += data[hour][minute];
}
if (m >= 40 && m < 60) {
memo[2] += data[hour][minute];
}
return memo;
}, [0, 0, 0]);
var h = parseInt(hour, 10);
total = total + buckets[0] + buckets[1] + buckets[2];
return [
{x: (60 * h), y: buckets[0] },
{x: (60 * h + 20), y: buckets[1] },
{x: (60 * h + 40), y: buckets[2] }
];
});
prepared = _.flatten(prepared);
var yMax = d3.max(prepared, function (d) { return d.y; });
var yScale = d3.scale.linear()
.domain([0, yMax])
.range([0, 60]);
return { total: total, prepared: prepared, yMax: yMax, yScale: yScale };
};
// below is sample data, example usage and the output of that usage logged out
// raw data for 2 hours, more likely up to 24hrs at a time
var raw_data = {
// first level is hours
"0": {
// second level is minute in hour
"25": 12,
"45": 12,
"15": 8,
"10": 16,
"55": 3,
"30": 8,
"50": 20,
"35": 8,
"0": 2,
"5": 5,
"40": 26,
"20": 13
},
"1": {
"25": 9,
"45": 5,
"15": 14,
"10": 9,
"55": 13,
"30": 15,
"50": 3,
"35": 5,
"0": 3,
"5": 9,
"40": 18,
"20": 13
}
};
var results = prep(raw_data);
console.log(results.total);
console.log(results.yMax);
console.log(results.prepared);
// The above three console.logs will output the following:
// $ node functional.js
// 249
// 61
// [ { x: 0, y: 31 },
// { x: 20, y: 41 },
// { x: 40, y: 61 },
// { x: 60, y: 35 },
// { x: 80, y: 42 },
// { x: 100, y: 39 } ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment