github.com/searKing/golang/go@v1.2.117/exp/slices/intersect.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  // Intersect returns a slice satisfying c != zero within all c in the slice.
     8  // Intersect does not modify the contents of the slice s1 and s2; it creates a new slice.
     9  func Intersect[S ~[]E, E comparable](s1, s2 S) S {
    10  	if len(s1) == 0 {
    11  		return s2
    12  	}
    13  	if len(s2) == 0 {
    14  		return s1
    15  	}
    16  	m := make(map[E]struct{})
    17  	for _, v := range s1 {
    18  		m[v] = struct{}{}
    19  	}
    20  
    21  	var ss S
    22  	for _, v := range s2 {
    23  		if len(m) == 0 {
    24  			break
    25  		}
    26  		if _, ok := m[v]; ok {
    27  			ss = append(ss, v)
    28  			delete(m, v)
    29  		}
    30  	}
    31  	return ss
    32  }
    33  
    34  // IntersectFunc returns a slice satisfying f(c) within all c in the slice.
    35  // IntersectFunc does not modify the contents of the slice s1 and s2; it creates a new slice.
    36  func IntersectFunc[S ~[]E, E any](s1, s2 S, f func(v1, v2 E) bool) S {
    37  	if len(s1) == 0 {
    38  		return s2
    39  	}
    40  	if len(s2) == 0 {
    41  		return s1
    42  	}
    43  
    44  	var ss S
    45  	for _, v := range s1 {
    46  		if ContainsFunc(ss, func(e E) bool { return f(v, e) }) {
    47  			continue
    48  		}
    49  		if ContainsFunc(s2, func(e E) bool { return f(v, e) }) {
    50  			ss = append(ss, v)
    51  		}
    52  	}
    53  	return ss
    54  }