Skip to content

Commit

Permalink
Add human-readable idle time in whois info
Browse files Browse the repository at this point in the history
  • Loading branch information
astorije committed Oct 27, 2016
1 parent e9b118e commit 6656b9c
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 0 deletions.
47 changes: 47 additions & 0 deletions client/js/libs/handlebars/humanReadableRange.js
@@ -0,0 +1,47 @@
"use strict";

Handlebars.registerHelper(
"humanReadableRange", function(seconds) {
var plural = function(number) {
return (number === 1) ? "" : "s";
};

if (seconds === 0) {
return "0 seconds";
}

var result = [];

var weeks = Math.floor(seconds / 604800);
if (weeks) {
result.push(weeks + " week" + plural(weeks));
}

var days = Math.floor((seconds %= 604800) / 86400);
if (days) {
result.push(days + " day" + plural(days));
}

var hours = Math.floor((seconds %= 86400) / 3600);
if (hours) {
result.push(hours + " hour" + plural(hours));
}

var minutes = Math.floor((seconds %= 3600) / 60);
if (minutes) {
result.push(minutes + " minute" + plural(minutes));
}

var remainingSeconds = seconds % 60;
if (remainingSeconds) {
result.push(remainingSeconds + " second" + plural(remainingSeconds));
}

var lastItem = result.pop();

if (result.length > 0) {
return result.join(", ") + " and " + lastItem;
}
return lastItem;
}
);
6 changes: 6 additions & 0 deletions client/views/actions/whois.tpl
Expand Up @@ -33,3 +33,9 @@
is away <i>({{whois.away}})</i>
</div>
{{/if}}
{{#if whois.idle}}
<div>
<span role="button" class="user {{colorClass whois.nick}}" data-name="{{whois.nick}}">{{whois.nick}}</span>
has been idle for {{humanReadableRange whois.idle}}.
</div>
{{/if}}
28 changes: 28 additions & 0 deletions test/client/js/libs/handlebars/humanReadableRangeTest.js
@@ -0,0 +1,28 @@
"use strict";

const Handlebars = global.Handlebars = require("handlebars");
const expect = require("chai").expect;

require("../../../../../client/js/libs/handlebars/humanReadableRange");

describe("humanReadableRange Handlebars helper", () => {
const template = Handlebars.compile("{{humanReadableRange range}}");

it("should build a simple range", () => {
expect(template({range: 30})).to.equal("30 seconds");
});

it("should not display zero values", () => {
expect(template({range: 86400 * 3 + 120})).to.equal("3 days and 2 minutes");
});

it("should pluralize things properly", () => {
expect(template({range: 3600})).to.equal("1 hour");
expect(template({range: 3600 * 2})).to.equal("2 hours");
});

it("should commas and 'and' in complex expressions", () => {
expect(template({range: 604800 + 86400 + 3600 + 60 + 1}))
.to.equal("1 week, 1 day, 1 hour, 1 minute and 1 second");
});
});

0 comments on commit 6656b9c

Please sign in to comment.