Skip to content

Instantly share code, notes, and snippets.

@yckart
Forked from 140bytes/LICENSE.txt
Last active December 21, 2015 23:39
Show Gist options
  • Save yckart/6383720 to your computer and use it in GitHub Desktop.
Save yckart/6383720 to your computer and use it in GitHub Desktop.
readingTime
function (
a, // a string
b, // words per minute
c, // minutes-placeholer
d // seconds-placeholder
) {
a = a.split(' ').length; // split each word
b = b || 180; // re-assign the wpm-rate
c = a / b | 0; // calculate the estimated seconds
d = a % b / (b / 60) | 0; // calculate the estimated seconds
return (c < 10 ? '0' + c : c) + ':' + (d < 10 ? '0' + d : d); // pad min and sec and output as mm:ss
}
function(a,b,c,d){a=a.split(' ').length;b=b||180;c=a/b|0;d=a%b/(b/60)|0;return(c<10?'0'+c:c)+':'+(d<10?'0'+d:d)}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2013 Yannick Albert <http://yckart.com>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "readingTime",
"description": "Calculate the time it takes to read a given amount of words.",
"keywords": [
"time",
"string",
"words",
"text",
"read"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b>00:03</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
var readingTime = function(a,b,c,d){a=a.split(' ').length;b=b||180;c=a/b|0;d=a%b/(b/60)|0;return(c<10?'0'+c:c)+':'+(d<10?'0'+d:d)};
document.getElementById('ret').innerHTML = readingTime('140byt.es is a tweet-sized, fork-to-play, community-curated collection of JavaScript');
</script>
@atk
Copy link

atk commented Aug 30, 2013

~ has higher precedence than /, but the precedence of | (bitwise or) is lower, so you can save some bytes by using |0 instead of ~~():

function(a,b,c,d){a=a.split(' ').length;b=b||180;c=a/b|0;d=a%b/(b/60)|0;return(c<10?'0':'')+c+':'+(d<10?'0':'')+d}

@yckart
Copy link
Author

yckart commented Aug 30, 2013

@atk Cool, did not know that! Merged it...

@atk
Copy link

atk commented Aug 30, 2013

@atk
Copy link

atk commented Sep 2, 2013

Save another 2 bytes by putting the string concatenation inside the query:

function(a,b,c,d){a=a.split(' ').length;b=b||180;c=a/b|0;d=a%b/(b/60)|0;return(c<10?'0'+c:c)+':'+(d<10?'0'+d:d)}

@yckart
Copy link
Author

yckart commented Sep 3, 2013

@atk Good point!

@atk
Copy link

atk commented Sep 4, 2013

To separate the float part, you can use %1, then reuse b and save another 5 bytes:

function(a,b,c){a=a.split(' ').length;c=a/(b||180);b=c%1*60|0;c|=0;return(c<10?'0'+c:c)+':'+(b<10?'0'+b:b)}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment