Skip to content

Instantly share code, notes, and snippets.

@hughevans
Last active December 15, 2015 12:38
Show Gist options
  • Select an option

  • Save hughevans/5261185 to your computer and use it in GitHub Desktop.

Select an option

Save hughevans/5261185 to your computer and use it in GitHub Desktop.
window.chapters = [];
var startTime = new Date('2012-06-11T11:10:00+10:00');
var processedChapters = 0;
// Loop through each of the nine chapters
for (var chapter = 0; chapter < 9; chapter++) {
// set up each chapter as an empty array to populate with the number of words
chapters[chapter] = [];
// Get the JSON data for the chapter’s versions
$.getJSON("/chapters/" + (chapter + 1) + "/versions", (function(chapter) {
return function(data) {
// Loop through 24 hours in 10 minute intervals
for (var interval = 0; interval < 144; interval++) {
var time = new Date(startTime);
time.setMinutes(startTime.getMinutes() + interval * 10);
// Find all versions before this time
var versions = $.grep(data.chapter_versions, function(version) {
return (new Date(version.created_at) < time);
});
// Select the newest version
var lastestVersion = versions[versions.length - 1];
var numWords = 0;
// Extract the number of words for the version (if there is one)
if (typeof lastestVersion !== "undefined") {
numWords = lastestVersion.text_analysis.num_words;
}
// Push the value to the chapter’s array
chapters[chapter].push(numWords);
}
// Because $.getJSON is async we need a way to tell when everything is done
processedChapters++;
if (processedChapters == 9) {
console.log('All data processed and saved to window.data');
console.log(window.chapters);
}
};
// Wrap in closure so the chapter variable stays correct
})(chapter));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment