Skip to content

Instantly share code, notes, and snippets.

@caleorourke
Created July 14, 2015 13:23
Show Gist options
  • Select an option

  • Save caleorourke/f184c073b65a861518fc to your computer and use it in GitHub Desktop.

Select an option

Save caleorourke/f184c073b65a861518fc to your computer and use it in GitHub Desktop.
/*
* Copyright © SoftLayer, an IBM Company
*
* guesstimate.js
* Urban's guesstimate.js script estimates how long it'll take to read a single page
* by converting the word count to minutes.
*
*/
(function($) {
$.fn.readEstimate = function(options) {
if (!this.length) {
return this;
}
var plugin = this;
el = $(this);
defaults = {
readOutput: '.estimate',
wordCount: null,
wordsPerMinute: 275,
roundup: true,
lessThanOneMinute: '',
prependTime: '',
prependWord: ''
};
plugin.settings = $.extend({}, defaults, options);
var readOutput = plugin.settings.readOutput;
wordCount = plugin.settings.wordCount;
wordsPerMinute = plugin.settings.wordsPerMinute;
roundup = plugin.settings.roundup;
lessThanOneMinute = plugin.settings.lessThanOneMinute;
prependTime = plugin.settings.prependTime;
prependWord = plugin.settings.prependWord;
if (wordCount < wordsPerMinute) {
var lessThanOneMinute = lessThanOneMinute || 'Less than a min read';
minuteOutput = 'min read';
}
var setTime = function(text) {
var totalWords = text.trim().split(/\s+/g).length;
wordsPerSecond = wordsPerMinute / 60;
totalTimeInSeconds = totalWords / wordsPerSecond;
if (roundup === true) {
readTimeInMinutes = Math.round(totalTimeInSeconds / 60);
} else {
Math.floor(totalTimeInSeconds / 60);
}
var readTimeInSeconds = Math.round(totalTimeInSeconds - readTimeInMinutes * 60);
if (roundup === true) {
if (readTimeInMinutes > 0) {
$(readOutput).text(prependTime + readTimeInMinutes + ' ' + minuteOutput);
} else {
$(readOutput).text(prependTime + lessThanOneMinute);
}
} else {
var readEstimate = readTimeInMinutes + ':' + readTimeInSeconds;
$(readOutput).text(prependTime + readEstimate);
}
if (wordCount !== '' && wordCount !== undefined) {
$(wordCount).text(prependWord + totalWords);
}
};
el.each(function() {
setTime(el.text());
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment