Last active
July 23, 2019 03:09
-
-
Save kerrishotts/e655d6c06374a778b153d48b0e5980aa to your computer and use it in GitHub Desktop.
2019-07-22 Dev.to challenge
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
| 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