Skip to content

Commit 3616a51

Browse files
feat: unwrap
1 parent 0dcb2bc commit 3616a51

2 files changed

Lines changed: 47 additions & 0 deletions

File tree

packages/pure-parse/src/parsers/ParseResult.test.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,11 @@ import {
1212
mapFailure,
1313
flatMapSuccess,
1414
flatMapFailure,
15+
unwrap,
1516
} from './ParseResult'
1617
import { Equals } from '../internals'
1718
import { parseNumber } from './primitives'
19+
import { formatResult } from './formatting'
1820

1921
describe('ParseResult', () => {
2022
describe('the `.error` property', () => {
@@ -208,4 +210,20 @@ describe('ParseResult', () => {
208210
})
209211
})
210212
})
213+
describe(unwrap, () => {
214+
it('returns the success value', () => {
215+
const res = success(77)
216+
const value = unwrap(res)
217+
expect(value).toBe(77)
218+
})
219+
it('throws on failure', () => {
220+
const res = failure('Cannot unwrap failure')
221+
expect(() => unwrap(res)).toThrow()
222+
})
223+
test('that the error contains the formatted Failure', () => {
224+
const message = 'Detailed error message'
225+
const res = failure(message)
226+
expect(() => unwrap(res)).toThrowError(new RegExp(formatResult(res)))
227+
})
228+
})
211229
})

packages/pure-parse/src/parsers/ParseResult.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { Parser } from './Parser'
2+
import { formatResult } from './formatting'
23

34
/*
45
* Type Definitions
@@ -213,3 +214,31 @@ export const flatMapFailure = <T>(
213214
result: ParseResult<T>,
214215
fn: (result: Failure) => ParseResult<T>,
215216
): ParseResult<T> => (isSuccess(result) ? result : fn(result.error))
217+
218+
const panic = (message: string): never => {
219+
throw new Error(message)
220+
}
221+
222+
/**
223+
* Unwrap a successful parsing result, or throw an error if it is a failure.
224+
* DANGER: This function can throw!
225+
* @example
226+
* Assert that a parsing result is successful:
227+
* ```ts
228+
* const result = parseNumberFromString('1')
229+
* const one = unwrap(result) // -> 123
230+
* const two = one + 1 // No need to map the Result type
231+
* ```
232+
* @example
233+
* But be aware, this _will_ throw if the result is a failure:
234+
* ```ts
235+
* const result = parseNumberFromString('abc')
236+
* const value = unwrap(result) // Throws!
237+
* const value2 = value + 1 // Never reached :(
238+
* ```
239+
* @param value
240+
*/
241+
export const unwrap = <T>(value: ParseResult<T>): T =>
242+
isSuccess(value)
243+
? value.value
244+
: panic(`Tried to unwrap a ParseFailure: ${formatResult(value)}`)

0 commit comments

Comments
 (0)