Skip to content

Commit 3607646

Browse files
Bart SchuurmansBartSchuurmans
Bart Schuurmans
authored andcommitted
Add Dict.mapValues
1 parent 7a29820 commit 3607646

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

src/Core__Dict.mjs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,18 @@ function forEachWithKey(dict, f) {
1717
});
1818
}
1919

20+
function mapValues(dict, f) {
21+
var target = {};
22+
forEachWithKey(dict, (function (value, key) {
23+
target[key] = f(value);
24+
}));
25+
return target;
26+
}
27+
2028
export {
2129
$$delete$1 as $$delete,
2230
forEach ,
2331
forEachWithKey ,
32+
mapValues ,
2433
}
2534
/* No side effect */

src/Core__Dict.res

Lines changed: 8 additions & 0 deletions
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

Lines changed: 14 additions & 0 deletions
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)