Skip to content

Commit

Permalink
fix: error when inner value is undefined
Browse files Browse the repository at this point in the history
  • Loading branch information
xuanduc987 committed Jun 8, 2021
1 parent e654e60 commit 61beb9b
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
12 changes: 6 additions & 6 deletions src/match.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ interface Match<Tag extends string> {
}

const tryMatch = (tag: string, [k, field, ...rest]: string[], v: any): unknown => {
if (!k) return [v]
if (k === '_') return [null]
if (v?.[tag] !== k) return
if (!v) return
if (!k) return v
if (k === '_') return null
if (v[tag] !== k) return
if (field) return tryMatch(tag, rest, v[field])
return v
return [v]
}

export const matchFor = <Tag extends string>(tag: Tag): Match<Tag> =>
Expand All @@ -28,8 +28,8 @@ export const matchFor = <Tag extends string>(tag: Tag): Match<Tag> =>
for (const [p, f] of Object.entries(pattern)) {
const ps = p === '_' ? ['_'] : p.split('_')
const m = tryMatch(tag, ps, value)
if (m !== undefined) {
return f(m ?? undefined)
if (m !== undefined && Array.isArray(m)) {
return f(m[0] ?? undefined)
}
}
throw new TypeError('Incomplete pattern!')
Expand Down
11 changes: 11 additions & 0 deletions test/matchWithSingle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,17 @@ import { none, Option, some } from './types/utils'

const match = matchWithFor('_tag')

test('option undefined', t => {
const o = some(void 0)
t.is(
match(o).with({
Some_value: () => 1,
None: () => 0,
}),
1,
)
})

test('option some', t => {
const o = some('TS')

Expand Down

0 comments on commit 61beb9b

Please sign in to comment.