1// Copyright 2024 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package maps
6
7import "iter"
8
9// All returns an iterator over key-value pairs from m.
10// The iteration order is not specified and is not guaranteed
11// to be the same from one call to the next.
12func All[Map ~map[K]V, K comparable, V any](m Map) iter.Seq2[K, V] {
13	return func(yield func(K, V) bool) {
14		for k, v := range m {
15			if !yield(k, v) {
16				return
17			}
18		}
19	}
20}
21
22// Keys returns an iterator over keys in m.
23// The iteration order is not specified and is not guaranteed
24// to be the same from one call to the next.
25func Keys[Map ~map[K]V, K comparable, V any](m Map) iter.Seq[K] {
26	return func(yield func(K) bool) {
27		for k := range m {
28			if !yield(k) {
29				return
30			}
31		}
32	}
33}
34
35// Values returns an iterator over values in m.
36// The iteration order is not specified and is not guaranteed
37// to be the same from one call to the next.
38func Values[Map ~map[K]V, K comparable, V any](m Map) iter.Seq[V] {
39	return func(yield func(V) bool) {
40		for _, v := range m {
41			if !yield(v) {
42				return
43			}
44		}
45	}
46}
47
48// Insert adds the key-value pairs from seq to m.
49// If a key in seq already exists in m, its value will be overwritten.
50func Insert[Map ~map[K]V, K comparable, V any](m Map, seq iter.Seq2[K, V]) {
51	for k, v := range seq {
52		m[k] = v
53	}
54}
55
56// Collect collects key-value pairs from seq into a new map
57// and returns it.
58func Collect[K comparable, V any](seq iter.Seq2[K, V]) map[K]V {
59	m := make(map[K]V)
60	Insert(m, seq)
61	return m
62}
63