File: slice.go

package info (click to toggle)
golang-github-juju-collections 1.0.4-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie, trixie-proposed-updates
  • size: 176 kB
  • sloc: makefile: 18
file content (46 lines) | stat: -rw-r--r-- 1,441 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Copyright 2022 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.

package transform

import (
	"fmt"
)

// Slice transforms a slice of one type to an equal length slice of another,
// by applying the input transformation function to each member.
func Slice[F any, T any](from []F, transform func(F) T) []T {
	to := make([]T, len(from))
	for i, oneFrom := range from {
		to[i] = transform(oneFrom)
	}
	return to
}

// SliceOrErr transforms a slice from one type to an equal length slice of another
// by mapping the input transformation function to each member.
// This differs from Slice in that the transform function can returns an error.
// If an error is encountered, the mapping will be cancelled and the error returned
func SliceOrErr[F any, T any](from []F, transform func(F) (T, error)) ([]T, error) {
	to := make([]T, len(from))
	for i, oneFrom := range from {
		var err error
		to[i], err = transform(oneFrom)
		if err != nil {
			return nil, fmt.Errorf("transforming slice at index %d: %w", i, err)
		}
	}
	return to, nil
}

// SliceToMap transforms a slice of one type to an equal length
// map with values from the slice, keyed by values indicated by
// the input transformation function.
func SliceToMap[F any, K comparable, V any](from []F, transform func(F) (K, V)) map[K]V {
	to := make(map[K]V, len(from))
	for _, oneFrom := range from {
		k, v := transform(oneFrom)
		to[k] = v
	}
	return to
}