Skip to content

Commit b37841e

Browse files
Bart SchuurmansBartSchuurmans
Bart Schuurmans
authored andcommitted
Add Dict.forEach and Dict.forEachWithKey
1 parent 51061a4 commit b37841e

File tree

3 files changed

+64
-0
lines changed

3 files changed

+64
-0
lines changed

src/Core__Dict.mjs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,27 @@
11
// Generated by ReScript, PLEASE EDIT WITH CARE
22

3+
import * as Curry from "rescript/lib/es6/curry.js";
34

45
function $$delete$1(dict, string) {
56
delete(dict[string]);
67
}
78

9+
function forEach(dict, f) {
10+
Object.keys(dict).forEach(function (key) {
11+
Curry._1(f, dict[key]);
12+
});
13+
}
14+
15+
function forEachWithKey(dict, f) {
16+
Object.keys(dict).forEach(function (key) {
17+
var value = dict[key];
18+
Curry._2(f, value, key);
19+
});
20+
}
21+
822
export {
923
$$delete$1 as $$delete,
24+
forEach ,
25+
forEachWithKey ,
1026
}
1127
/* No side effect */

src/Core__Dict.res

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,21 @@ let delete = (dict, string) => {
2323
@val external assign: (t<'a>, t<'a>) => t<'a> = "Object.assign"
2424

2525
@val external copy: (@as(json`{}`) _, t<'a>) => t<'a> = "Object.assign"
26+
27+
let forEach = (dict, f) => {
28+
dict
29+
->keysToArray
30+
->Core__Array.forEach(key => {
31+
let value = dict->getUnsafe(key)
32+
f(value)
33+
})
34+
}
35+
36+
let forEachWithKey = (dict, f) => {
37+
dict
38+
->keysToArray
39+
->Core__Array.forEach(key => {
40+
let value = dict->getUnsafe(key)
41+
f(value, key)
42+
})
43+
}

src/Core__Dict.resi

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,3 +189,33 @@ Console.log2(dict->Dict.keysToArray, dict2->Dict.keysToArray)
189189
*/
190190
@val
191191
external copy: (@as(json`{}`) _, t<'a>) => t<'a> = "Object.assign"
192+
193+
/**
194+
`forEach(dictionary, f)` iterates through all values of the dict.
195+
196+
> Please note that this is *without the keys*, just the values. If you need the key as well, use `Dict.forEachWithKey`.
197+
198+
## Examples
199+
```rescript
200+
let dict = Dict.fromArray([("key1", "value1"), ("key2", "value2")])
201+
202+
dict->Dict.forEach(value => {
203+
Console.log(value)
204+
})
205+
```
206+
*/
207+
let forEach: (t<'a>, 'a => unit) => unit
208+
209+
/**
210+
`forEachWithKey(dictionary, f)` iterates through all values of the dict, including the key for each value.
211+
212+
## Examples
213+
```rescript
214+
let dict = Dict.fromArray([("key1", "value1"), ("key2", "value2")])
215+
216+
dict->Dict.forEachWithKey((value, key) => {
217+
Console.log2(value, key)
218+
})
219+
```
220+
*/
221+
let forEachWithKey: (t<'a>, ('a, string) => unit) => unit

0 commit comments

Comments
 (0)