Skip to content

Commit

Permalink
Merge pull request #10 from boivie/units_option
Browse files Browse the repository at this point in the history
Units option
  • Loading branch information
domchristie committed Nov 29, 2014
2 parents 36e534e + 595ba72 commit 51473c5
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ Usage
juration.stringify(185, { format: 'small' }); // returns "3 mins 5 secs"
juration.stringify(185, { format: 'micro' }); // returns "3m 5s"
juration.stringify(185, { format: 'long' }); // returns "3 minutes 5 seconds"
juration.stringify(185, { format: 'long', units: 1 }); // returns "3 minutes"
juration.stringify(3601, { format: 'micro', units: 2 }); // returns "1h"

Examples
--------
Expand Down
10 changes: 8 additions & 2 deletions juration.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,16 +93,22 @@
}

var defaults = {
format: 'short'
format: 'short',
units: undefined
};

var opts = _extend(defaults, options);

var units = ['years', 'months', 'days', 'hours', 'minutes', 'seconds'], values = [];
var remaining = seconds;
for(var i = 0, len = units.length; i < len; i++) {
var activeUnits = 0;
for(var i = 0, len = units.length;
i < len && (opts.units == undefined || activeUnits < opts.units);
i++) {
var unit = UNITS[units[i]];
values[i] = Math.floor(remaining / unit.value);
if (values[i] > 0 || activeUnits > 0)
activeUnits++;

if(opts.format === 'micro' || opts.format === 'chrono') {
values[i] += unit.formats[opts.format];
Expand Down
22 changes: 22 additions & 0 deletions test/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,28 @@
}
});

test("stringifying with 'units' option", function() {
var testCases = [
[5, "", 0],
[5, "5 seconds", 1],
[5, "5 seconds", 2],
[5 * 60 + 5, "5 minutes", 1],
[5 * 60 + 5, "5 minutes 5 seconds", 2],
[5 * 60 + 5, "5 minutes 5 seconds", 3],
[5 * 3600 + 5 * 60 + 5, "5 hours", 1],
[5 * 3600 + 5 * 60 + 5, "5 hours 5 minutes", 2],
[5 * 3600 + 5 * 60 + 5, "5 hours 5 minutes 5 seconds", 3],
[5 * 3600 + 5 * 60 + 5, "5 hours 5 minutes 5 seconds", 4],
[5 * 3600 + 0 * 60 + 5, "5 hours", 2],
[5 * 3600 + 0 * 60 + 5, "5 hours 5 seconds", 3]
];

for(var i = 0, len = testCases.length; i < len; i++) {
var parsed = juration.stringify(testCases[i][0], { format: 'long', units: testCases[i][2] });
equal(parsed, testCases[i][1], "We expect " + testCases[i][0] + " with units " + testCases[i][2] + " to be " + testCases[i][1]);
}
});

test("stringifying non-numeric values", function() {
var testCases = [
["", "juration.stringify(): Unable to stringify a non-numeric value"],
Expand Down

0 comments on commit 51473c5

Please sign in to comment.