DEV Community

Discussion on: Daily Challenge #21 - Human Readable Time

Collapse
 
kerrishotts profile image
Kerri Shotts

Easy to muck up, that's for sure. For awhile, I had this thing trying to say that 3600 was equal to several days (instead of an hour).

Quite enjoyable. Turns out that Wolfram Alpha stops being terribly useful if you give it a large number of seconds, so had to go "sure, that looks right" a couple times.

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";

Gist: gist.github.com/kerrishotts/e655d6...