Last active
April 12, 2018 14:02
-
-
Save aliaspooryorik/2edc95521ccb64ae44dc25b52b972ccd to your computer and use it in GitHub Desktop.
humaniseSeconds
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <cfscript> | |
| // Kudos to Jamie Purchase | |
| function humaniseSeconds(seconds) { | |
| var result = []; | |
| var parts = createObject("java", "java.util.LinkedHashMap").init(); | |
| parts["week"] = (3600 * 24) * 7; | |
| parts["day"] = (3600 * 24); | |
| parts["hour"] = 60 * 60; | |
| parts["minute"] = 60; | |
| parts["second"] = 1; | |
| var plural = function(label, unit) { | |
| label &= unit > 1 ? 's' : ''; | |
| return unit & " " & label; | |
| }; | |
| structEach(parts, function(key, value) { | |
| if (seconds > 0) { | |
| var unit = int(seconds / value); | |
| if (unit > 0) { | |
| seconds -= unit * value; | |
| arrayAppend(result, plural(key, unit)); | |
| } | |
| } | |
| }); | |
| return arrayToList(result, ", "); | |
| } | |
| function assert(expected, actual) { | |
| var pass = expected == actual; | |
| writeOutput("pass: #pass# | #expected# == #actual#<br>"); | |
| } | |
| assert("1 minute, 1 second", humaniseSeconds(61)); | |
| assert("2 minutes, 2 seconds", humaniseSeconds(122)); | |
| assert("1 hour, 3 seconds", humaniseSeconds(3603)); | |
| assert("2 hours, 1 minute, 3 seconds", humaniseSeconds(7263)); | |
| assert("1 week, 2 hours, 1 minute, 3 seconds", humaniseSeconds(612063)); | |
| </cfscript> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment