From a8025b538b59d501de275495e1ef843bce69dc5c Mon Sep 17 00:00:00 2001 From: Rohit Tanwar <31792358+kriadmin@users.noreply.github.com> Date: Thu, 4 Jan 2018 12:56:42 +0530 Subject: [PATCH] Create formatDuration.md --- snippets/formatDuration.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 snippets/formatDuration.md diff --git a/snippets/formatDuration.md b/snippets/formatDuration.md new file mode 100644 index 000000000..ea8e3325b --- /dev/null +++ b/snippets/formatDuration.md @@ -0,0 +1,25 @@ +###formatDuration + +Returns the human readable format of the given number of milliseconds. If milliseconds is equal to `0` return `'now'` . + +``` js +const formatDuration = milliseconds => { +if(milliseconds === 0) return 'now' +if(milliseconds < 0) milliseconds = -milliseconds +const join = (arr, separator = ',', end = separator) => + arr.reduce( + (acc, val, i) => + i == arr.length - 2 + ? acc + val + end + : i == arr.length - 1 ? acc + val : acc + val + separator, + '' + ); +const pluralize = (num, word, plural = word + 's') => + Number(num) === 1 ? word : plural; + let date = new Date(milliseconds) + let array = [date.getUTCMilliseconds(),date.getUTCSeconds(),date.getUTCMinutes(),date.getUTCHours(),date.getUTCDate()-1,date.getUTCMonth(),date.getUTCFullYear()-1970] + let time = ["millisecond","second","minute","hour","day","month","year"] + array = array.map((el,i) => [el,time[i]]).filter(el => el[0] !== 0).map(el => [el[0],pluralize(el[0],el[1])]).map(el => el[0] + ' ' + el[1]) + return join(array.reverse(),', ',' and ') +} +```