Skip to content

Commit

Permalink
Add Map.values_mut
Browse files Browse the repository at this point in the history
This method is used to iterate over mutable references to values in a
Map.

This fixes #544.

Changelog: added
  • Loading branch information
yorickpeterse committed Jun 13, 2023
1 parent 1e4566e commit 97d195a
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
20 changes: 19 additions & 1 deletion std/src/std/map.inko
Expand Up @@ -257,7 +257,8 @@ class pub Map[K: Hash + Equal[K], V] {
iter.map fn (e) { e.key }
}

# Returns an `Iter` visiting all the values in this `Map`.
# Returns an iterator that yields immutable references to the values in
# `self`.
#
# # Examples
#
Expand Down Expand Up @@ -556,6 +557,23 @@ impl Map if V: mut {
case index -> @entries.get_mut(index).value
}
}

# Returns an iterator that yields mutable references to the values in `self`.
#
# # Examples
#
# Iterating over the values in a `Map`:
#
# let mut map = Map.new
#
# map.set('name', 'Alice')
#
# map.values_mut.each fn (value) {
# value # => 'Alice'
# }
fn pub mut values_mut -> Iter[mut V] {
iter_mut.map fn (e) { e.value }
}
}

impl Equal[Map[K, V]] for Map if V: Equal[V] {
Expand Down
10 changes: 10 additions & 0 deletions std/test/std/test_map.inko
Expand Up @@ -120,6 +120,16 @@ fn pub tests(t: mut Tests) {
t.true(values.get(0) == 'Alice' or values.get(0) == 'Bla')
}

t.test('Map.values_mut') fn (t) {
let map = Map.new

map.set('numbers', [10])

map.values_mut.each fn (nums) { nums.push(20) }

t.equal(map.opt('numbers'), Option.Some(ref [10, 20]))
}

t.test('Map.opt') fn (t) {
let map = Map.new

Expand Down

0 comments on commit 97d195a

Please sign in to comment.