about summary refs log tree commit diff
diff options
context:
space:
mode:
authorBossett <bossett@bossett.io>2023-09-09 01:57:22 +1000
committerGitHub <noreply@github.com>2023-09-08 08:57:22 -0700
commit775aa875404898ad727960b28c6b271a5a381864 (patch)
treea74830836ace051622543cc013ff39b22a234f8b
parent6d73ed96e1d6bccfa60113727571411f06a2b172 (diff)
downloadvoidsky-775aa875404898ad727960b28c6b271a5a381864.tar.zst
Update time.ts to handle very small or negative time differences (#1390)
* Update time.ts to handle very small or negative time differences

Right now, posts can appear to be from the future with a negative time difference (i.e. -3s appears). This change defines 'NOW' as less than 5 seconds old, and returns 'now' in that case.

It's not clear how localisation is handled - this may need translation.

* Add test for 'now' in time/ago(...)

Add tests for ago() for right now (i.e. 'now') and 10s ago to ensure the seconds case is still tested
-rw-r--r--__tests__/lib/string.test.ts4
-rw-r--r--src/lib/strings/time.ts5
2 files changed, 7 insertions, 2 deletions
diff --git a/__tests__/lib/string.test.ts b/__tests__/lib/string.test.ts
index 726c9be94..63bd785ea 100644
--- a/__tests__/lib/string.test.ts
+++ b/__tests__/lib/string.test.ts
@@ -175,6 +175,7 @@ describe('ago', () => {
     1671461038,
     '04 Dec 1995 00:12:00 GMT',
     new Date(),
+    new Date().setSeconds(new Date().getSeconds() - 10),
     new Date().setMinutes(new Date().getMinutes() - 10),
     new Date().setHours(new Date().getHours() - 1),
     new Date().setDate(new Date().getDate() - 1),
@@ -183,7 +184,8 @@ describe('ago', () => {
   const outputs = [
     new Date(1671461038).toLocaleDateString(),
     new Date('04 Dec 1995 00:12:00 GMT').toLocaleDateString(),
-    '0s',
+    'now',
+    '10s',
     '10m',
     '1h',
     '1d',
diff --git a/src/lib/strings/time.ts b/src/lib/strings/time.ts
index 588b84459..05a60e94b 100644
--- a/src/lib/strings/time.ts
+++ b/src/lib/strings/time.ts
@@ -1,3 +1,4 @@
+const NOW = 5
 const MINUTE = 60
 const HOUR = MINUTE * 60
 const DAY = HOUR * 24
@@ -13,7 +14,9 @@ export function ago(date: number | string | Date): string {
     ts = date
   }
   const diffSeconds = Math.floor((Date.now() - ts) / 1e3)
-  if (diffSeconds < MINUTE) {
+  if (diffSeconds < NOW) {
+    return `now`
+  } else if (diffSeconds < MINUTE) {
     return `${diffSeconds}s`
   } else if (diffSeconds < HOUR) {
     return `${Math.floor(diffSeconds / MINUTE)}m`