go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/iter/insert_sorted_by.go (about)

     1  /*
     2  
     3  Copyright (c) 2023 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package iter
     9  
    10  import (
    11  	"cmp"
    12  	"slices"
    13  )
    14  
    15  // InsertSortedBy performs an insertion at the index that would satisfy
    16  // that the resulting array would be sorted ascending, provided a given
    17  // value extractor for the elements.
    18  func InsertSortedBy[V any, K cmp.Ordered](working []V, v V, fn func(V) K) []V {
    19  	searchFunc := func(a, b V) int {
    20  		ak := fn(a)
    21  		bk := fn(b)
    22  		if ak > bk {
    23  			return 1
    24  		}
    25  		if ak == bk {
    26  			return 0
    27  		}
    28  		return -1
    29  	}
    30  	insertAt, _ := slices.BinarySearchFunc(working, v, searchFunc)
    31  	working = append(working, v)
    32  	copy(working[insertAt+1:], working[insertAt:])
    33  	working[insertAt] = v
    34  	return working
    35  }