github.com/searKing/golang/go@v1.2.117/exp/slices/map.go (about)

     1  // Copyright 2022 The searKing Author. 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  
     5  package slices
     6  
     7  import "fmt"
     8  
     9  // Map returns a slice mapped by format "%v" within all c in the slice.
    10  // Map does not modify the contents of the slice s; it creates a new slice.
    11  // TODO: accept [S ~[]E, E any, R ~[]M, M ~string] if go support template type deduction
    12  func Map[S ~[]E, E any, R []M, M string](s S) R {
    13  	return MapFunc(s, func(e E) M {
    14  		return M(fmt.Sprintf("%v", e))
    15  	})
    16  }
    17  
    18  // MapFunc returns a slice mapped by f(c) within all c in the slice.
    19  // MapFunc does not modify the contents of the slice s; it creates a new slice.
    20  // TODO: accept [S ~[]E, E any, R ~[]M, M any] if go support template type deduction
    21  func MapFunc[S ~[]E, E any, R []M, M any](s S, f func(E) M) R {
    22  	return MapIndexFunc(s, func(i int, e E) M {
    23  		return f(e)
    24  	})
    25  }
    26  
    27  // MapIndexFunc works like MapFunc, returns a slice mapped by f(i, c) within all c in the slice.
    28  // MapIndexFunc does not modify the contents of the slice s; it creates a new slice.
    29  // TODO: accept [S ~[]E, E any, R ~[]M, M any] if go support template type deduction
    30  func MapIndexFunc[S ~[]E, E any, R []M, M any](s S, f func(i int, e E) M) R {
    31  	if s == nil {
    32  		return nil
    33  	}
    34  
    35  	var rr = make(R, len(s))
    36  	for i, v := range s {
    37  		rr[i] = f(i, v)
    38  	}
    39  	return rr
    40  }