Skip to content

Commit e1c4c36

Browse files
Bart SchuurmansBartSchuurmans
Bart Schuurmans
authored andcommitted
Add Dict.mapValues
1 parent e07ad91 commit e1c4c36

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

src/Core__Dict.mjs

+9
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,18 @@ function forEachWithKey(dict, f) {
1616
});
1717
}
1818

19+
function mapValues(dict, f) {
20+
var target = {};
21+
forEachWithKey(dict, (function (value, key) {
22+
target[key] = Curry._1(f, value);
23+
}));
24+
return target;
25+
}
26+
1927
export {
2028
$$delete$1 as $$delete,
2129
forEach ,
2230
forEachWithKey ,
31+
mapValues ,
2332
}
2433
/* No side effect */

src/Core__Dict.res

+8
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,11 @@ let forEach = (dict, f) => {
3131
let forEachWithKey = (dict, f) => {
3232
dict->toArray->Core__Array.forEach(((key, value)) => f(value, key))
3333
}
34+
35+
let mapValues = (dict, f) => {
36+
let target = make()
37+
dict->forEachWithKey((value, key) => {
38+
target->set(key, f(value))
39+
})
40+
target
41+
}

src/Core__Dict.resi

+14
Original file line numberDiff line numberDiff line change
@@ -220,3 +220,17 @@ dict->Dict.forEachWithKey((value, key) => {
220220
```
221221
*/
222222
let forEachWithKey: (t<'a>, ('a, string) => unit) => unit
223+
224+
/**
225+
`mapValues(dictionary, f)` returns a new dictionary with the same keys, and `f` applied to each value in the original dictionary.
226+
227+
## Examples
228+
229+
```rescript
230+
let dict = Dict.fromArray([("key1", 1), ("key2", 2)])
231+
232+
dict->Dict.mapValues(v => v + 10)->Dict.toArray // [("key1", 11), ("key2", 12)]
233+
dict->Dict.mapValues(Int.toString)->Dict.toArray // [("key1", "1"), ("key2", "2")]
234+
```
235+
*/
236+
let mapValues: (t<'a>, 'a => 'b) => t<'b>

0 commit comments

Comments
 (0)