Skip to content

Commit 5d769e9

Browse files
authored
Add alternative for dict{} pattern match (#7989)
* Add alternative for dict{} pattern match * 🔨 😱 ©️
1 parent 68afeab commit 5d769e9

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

packages/@rescript/runtime/Stdlib_Dict.resi

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,36 @@ switch dict->Dict.get("someKey") {
3737
| Some(value) => Console.log(value)
3838
}
3939
```
40+
41+
## Alternative: Pattern Matching with `dict{}`
42+
43+
For nested dictionary access, consider using the more concise `dict{}` pattern matching syntax:
44+
45+
```rescript
46+
// More concise approach using pattern matching
47+
let decodeImageUrl = (json: JSON.t) => {
48+
switch json {
49+
| JSON.Object(dict{"data": JSON.Object(dict{"image_url": JSON.String(url)})}) => Some(url)
50+
| _ => None
51+
}
52+
}
53+
54+
// Alternative using Dict.get
55+
let decodeImageUrl = (json: JSON.t) => {
56+
switch json {
57+
| JSON.Object(obj) =>
58+
switch Dict.get(obj, "data") {
59+
| Some(JSON.Object(data)) =>
60+
switch Dict.get(data, "image_url") {
61+
| Some(JSON.String(url)) => Some(url)
62+
| _ => None
63+
}
64+
| _ => None
65+
}
66+
| _ => None
67+
}
68+
}
69+
```
4070
*/
4171
@get_index
4272
external get: (dict<'a>, string) => option<'a> = ""

0 commit comments

Comments
 (0)