Skip to content

Commit 6c5c2ba

Browse files
authored
fix(hash/equal): prevent defects with invalid date (#5878)
1 parent d739bee commit 6c5c2ba

File tree

5 files changed

+34
-2
lines changed

5 files changed

+34
-2
lines changed

.changeset/rude-things-carry.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"effect": patch
3+
---
4+
5+
prevent crash from Hash and Equal with invalid Date object

packages/effect/src/Equal.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,9 @@ function compareBoth(self: unknown, that: unknown): boolean {
5252
: false
5353
}
5454
} else if (self instanceof Date && that instanceof Date) {
55-
return self.toISOString() === that.toISOString()
55+
const t1 = self.getTime()
56+
const t2 = that.getTime()
57+
return t1 === t2 || (Number.isNaN(t1) && Number.isNaN(t2))
5658
} else if (self instanceof URL && that instanceof URL) {
5759
return self.href === that.href
5860
}

packages/effect/src/Hash.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,9 @@ export const hash: <A>(self: A) => number = <A>(self: A) => {
5353
if (self === null) {
5454
return string("null")
5555
} else if (self instanceof Date) {
56+
if (Number.isNaN(self.getTime())) {
57+
return string("Invalid Date")
58+
}
5659
return hash(self.toISOString())
5760
} else if (self instanceof URL) {
5861
return hash(self.href)

packages/effect/test/Equal.test.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { describe, it } from "@effect/vitest"
2+
import { assertFalse, assertTrue } from "@effect/vitest/utils"
3+
import { Equal } from "effect"
4+
5+
describe("Equal", () => {
6+
it("invalid Date", () => {
7+
const d1 = new Date("invalid")
8+
const d2 = new Date("invalid")
9+
assertTrue(Equal.equals(d1, d2))
10+
})
11+
12+
it("Date(0) vs invalid Date", () => {
13+
const epoch = new Date(0)
14+
const invalid = new Date("invalid")
15+
assertFalse(Equal.equals(epoch, invalid))
16+
})
17+
})

packages/effect/test/Hash.test.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { describe, it } from "@effect/vitest"
1+
import { describe, expect, it } from "@effect/vitest"
22
import { assertFalse, assertTrue, strictEqual } from "@effect/vitest/utils"
33
import { absurd, Equal, Hash, HashSet, identity, Option, Utils } from "effect"
44

@@ -72,4 +72,9 @@ describe("Hash", () => {
7272
assertFalse(Hash.isHash(null))
7373
assertFalse(Hash.isHash({}))
7474
})
75+
76+
it("invalid Date", () => {
77+
const invalidDate = new Date("invalid")
78+
expect(() => Hash.hash(invalidDate)).not.toThrow()
79+
})
7580
})

0 commit comments

Comments
 (0)