Skip to content

Commit 16e4a84

Browse files
committed
feat(option): add expect
1 parent ce95b60 commit 16e4a84

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
@@ -40,6 +40,17 @@ function getExn(x) {
4040
};
4141
}
4242

43+
function expect(opt, message) {
44+
if (opt !== undefined) {
45+
return Caml_option.valFromOption(opt);
46+
}
47+
throw {
48+
RE_EXN_ID: "Failure",
49+
_1: message,
50+
Error: new Error()
51+
};
52+
}
53+
4354
function mapWithDefault(opt, $$default, f) {
4455
var f$1 = Curry.__1(f);
4556
if (opt !== undefined) {
@@ -123,6 +134,7 @@ export {
123134
filter ,
124135
forEach ,
125136
getExn ,
137+
expect ,
126138
mapWithDefault ,
127139
map ,
128140
flatMap ,

src/Core__Option.res

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

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

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

src/Core__Option.resi

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

106+
/**
107+
`expect(opt, message)` returns `value` if `Some(value)`, raises a `Failure` expection with the given message if `None`.
108+
109+
```rescript
110+
Option.expect(Some(3), "should not be None") // 3
111+
Option.expect(None, "should not be None") // Raises `Failure("should not be None")`
112+
```
113+
114+
## Exceptions
115+
116+
- Raises `Failure` if `opt` is `None`
117+
*/
118+
let expect: (option<'a>, string) => 'a
119+
106120
/**
107121
`getUnsafe(value)` returns `value`.
108122

0 commit comments

Comments
 (0)