Skip to content

Commit

Permalink
Merge pull request #57 from unsplash/matchx-undefined
Browse files Browse the repository at this point in the history
  • Loading branch information
mlegenhausen authored Jun 5, 2023
2 parents 7f3a07c + 13c9b30 commit be211e1
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
7 changes: 3 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -256,13 +256,12 @@ const mkMatchXW =
<C extends B[keyof B]>(x: A): C => {
const tag = x[tagKey] as Tag<A>

const g = fs[tag]
// eslint-disable-next-line functional/no-conditional-statement, @typescript-eslint/no-unsafe-return
if (g !== undefined) return g as C
if (Object.prototype.hasOwnProperty.call(fs, tag)) return fs[tag] as C

const h = (fs as CasesXWildcard<A, B>)[_]
// eslint-disable-next-line functional/no-conditional-statement, @typescript-eslint/no-unsafe-return
if (h !== undefined) return h as C
if (Object.prototype.hasOwnProperty.call(fs, _))
return (fs as CasesXWildcard<A, B>)[_] as C

// eslint-disable-next-line functional/no-throw-statement
throw new Error(`Failed to pattern match against tag "${tag}".`)
Expand Down
32 changes: 32 additions & 0 deletions test/unit/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,22 @@ describe("index", () => {
expect(f(Weather.mk.Sun)).toBe("didn't rain")
})

it("matchX allow undefined value", () => {
type T = Member<"A"> | Member<"B"> | Member<"toString">
const T = create<T>()

const f = T.matchX({
A: undefined,
[_]: undefined,
})

expect(f(T.mk.A)).toBe(undefined)
expect(f(T.mk.B)).toBe(undefined)
// Check that `toString` does not match an object prototype function
// This check would fail when the `in` operator is used instead of `hasOwnProperty`.
expect(f(T.mk.toString)).toBe(undefined)
})

it("matchXW", () => {
const f = Weather.matchXW({
Rain: "rained",
Expand All @@ -98,6 +114,22 @@ describe("index", () => {

expect(f(Weather.mk.Sun)).toBeNull()
})

it("matchXW allow undefined value", () => {
type T = Member<"A"> | Member<"B"> | Member<"toString">
const T = create<T>()

const f = T.matchXW({
A: undefined,
[_]: undefined,
})

expect(f(T.mk.A)).toBe(undefined)
expect(f(T.mk.B)).toBe(undefined)
// Check that `toString` does not match an object prototype function.
// This check would fail when the `in` operator is used instead of `hasOwnProperty`.
expect(f(T.mk.toString)).toBe(undefined)
})
})
})

Expand Down

0 comments on commit be211e1

Please sign in to comment.