diff options
author | Eugene Sokolov <eug-vs@keemail.me> | 2020-10-10 12:14:04 +0300 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-10-10 12:14:04 +0300 |
commit | e7fb5387af7d3397df49b913795b956fc375e39d (patch) | |
tree | c10166f9d4a132855c4d4ff26295760fd654c12c /src/components/DateString/compactDateString.ts | |
parent | 40ac5922118015aae943872717730d7068976b1a (diff) | |
parent | 5ee4f42b577449a58469fd3c7892455d097a6c79 (diff) | |
download | which-ui-e7fb5387af7d3397df49b913795b956fc375e39d.tar.gz |
Merge pull request #106 from which-ecosystem/feat/date-format
Imrove date formats
Diffstat (limited to 'src/components/DateString/compactDateString.ts')
-rw-r--r-- | src/components/DateString/compactDateString.ts | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/src/components/DateString/compactDateString.ts b/src/components/DateString/compactDateString.ts new file mode 100644 index 0000000..8bff4b7 --- /dev/null +++ b/src/components/DateString/compactDateString.ts @@ -0,0 +1,35 @@ +const metrics = [ + { name: 'minute', ratio: 60 }, + { name: 'hour', ratio: 60 }, + { name: 'day', ratio: 24 }, + { name: 'week', ratio: 7 }, + { name: 'month', ratio: 4 }, + { name: 'year', ratio: 12 } +]; + +const PRECISION = 0.85; + +const resolve = (value: number, metricIndex = 0): string => { + // Recursively divide value until it's ready to be presented as a string + const metric = metrics[metricIndex]; + const nextMetric = metrics[metricIndex + 1]; + const newValue = value / metric.ratio; + + if (newValue < nextMetric.ratio * PRECISION) { + const rounded = Math.round(newValue); + const isPlural = rounded > 1; + const count = isPlural ? rounded : 'a'; + const ending = isPlural ? 's' : ''; + return `${count} ${metric.name}${ending} ago`; + } + return resolve(newValue, metricIndex + 1); +}; + +const compactDateString = (date: Date): string => { + const now = new Date(); + const diff = (now.valueOf() - date.valueOf()) / 1000; + if (diff < 60) return 'just now'; + return resolve(diff); +}; + +export default compactDateString; |