Skip to content

Commit 20c9723

Browse files
committed
feat(option): add expect
1 parent 29d8471 commit 20c9723

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed

src/Core__Option.mjs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,17 @@ function getExn(x) {
3636
};
3737
}
3838

39+
function expect(opt, message) {
40+
if (opt !== undefined) {
41+
return Caml_option.valFromOption(opt);
42+
}
43+
throw {
44+
RE_EXN_ID: "Failure",
45+
_1: message,
46+
Error: new Error()
47+
};
48+
}
49+
3950
function mapWithDefault(opt, $$default, f) {
4051
var f$1 = Curry.__1(f);
4152
if (opt !== undefined) {
@@ -118,6 +129,7 @@ export {
118129
filter ,
119130
forEach ,
120131
getExn ,
132+
expect ,
121133
mapWithDefault ,
122134
map ,
123135
flatMap ,

src/Core__Option.res

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,12 @@ let getExn = x =>
5050
| None => raise(Not_found)
5151
}
5252

53+
let expect = (opt, message) =>
54+
switch opt {
55+
| Some(value) => value
56+
| None => raise(Failure(message))
57+
}
58+
5359
external getUnsafe: option<'a> => 'a = "%identity"
5460

5561
let mapWithDefaultU = (opt, default, f) =>

src/Core__Option.resi

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,20 @@ Option.getExn(None) /* Raises an Error */
9191
*/
9292
let getExn: option<'a> => 'a
9393

94+
/**
95+
`expect(opt, message)` returns `value` if `Some(value)`, raises a `Failure` expection with the given message if `None`.
96+
97+
```rescript
98+
Option.expect(Some(3), "should not be None") // 3
99+
Option.expect(None, "should not be None") // Raises `Failure("should not be None")`
100+
```
101+
102+
## Exceptions
103+
104+
- Raises `Failure` if `opt` is `None`
105+
*/
106+
let expect: (option<'a>, string) => 'a
107+
94108
/**
95109
`getUnsafe(value)` returns `value`.
96110

0 commit comments

Comments
 (0)