Skip to content

Instantly share code, notes, and snippets.

@kerrishotts

kerrishotts/20190722.js

Last active Jul 23, 2019
Embed
What would you like to do?
2019-07-22 Dev.to challenge
const notEmpty = i => i !== "";
const singularize = str => str.substr(0, str.length - 1);
const englishJoin = (str, part, idx, arr) => str + ((idx === arr.length - 1 && arr.length > 1) ? " and " : ( str && ", ")) + part;
const spellInterval = (seconds = 0) =>
Object.entries({
years: 365 * 24 * 60 * 60,
days: 24 * 60 * 60,
hours: 60 * 60,
minutes: 60,
seconds: 1
}).reduce(({secondsRemaining, spelling}, [units, place]) => {
const v = Math.floor(secondsRemaining / place);
return {
secondsRemaining: secondsRemaining % place,
spelling: [...spelling, v ? `${v} ${v === 1 ? singularize(units) : units}` : ""]
};
}, { secondsRemaining: seconds, spelling: []})
.spelling
.filter(notEmpty)
.reduce(englishJoin, "")
.trim() || "now";
const expect = require("chai").expect;
expect(spellInterval(0)).to.equal("now");
expect(spellInterval(1)).to.equal("1 second");
expect(spellInterval(2)).to.equal("2 seconds");
expect(spellInterval(10)).to.equal("10 seconds");
expect(spellInterval(59)).to.equal("59 seconds");
expect(spellInterval(60)).to.equal("1 minute");
expect(spellInterval(120)).to.equal("2 minutes");
expect(spellInterval(121)).to.equal("2 minutes and 1 second");
expect(spellInterval(600)).to.equal("10 minutes");
expect(spellInterval(6000)).to.equal("1 hour and 40 minutes");
expect(spellInterval(123000)).to.equal("1 day, 10 hours and 10 minutes");
expect(spellInterval(95738532)).to.equal("3 years, 13 days, 2 hours, 2 minutes and 12 seconds");
expect(spellInterval(365 * 24 * 60 * 60)).to.equal("1 year");
expect(spellInterval(10 * 365 * 24 * 60 * 60)).to.equal("10 years");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.