Debian Codegraph @

exslices/delete.go

raw
1 // Copyright (c) 2025 Tulir Asokan
2 //
3 // This Source Code Form is subject to the terms of the Mozilla Public
4 // License, v. 2.0. If a copy of the MPL was not distributed with this
5 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7 package exslices
8
9 import (
10 "slices"
11 )
12
13 // FastDeleteIndex deletes the item at the given index without preserving slice order.
14 // This is faster than normal deletion, as it doesn't need to copy all elements after the deleted index.
15 func FastDeleteIndex[T any](s []T, index int) []T {
16 s[index] = s[len(s)-1]
17 clear(s[len(s)-1:])
18 return s[:len(s)-1]
19 }
20
21 // FastDeleteItem finds the first index of the given item in the slice and deletes it without preserving slice order.
22 // This is faster than normal deletion, as it doesn't need to copy all elements after the deleted index.
23 func FastDeleteItem[T comparable](s []T, item T) []T {
24 index := slices.Index(s, item)
25 if index < 0 {
26 return s
27 }
28 return FastDeleteIndex(s, index)
29 }
30
31 // DeleteItem finds the first index of the given item in the slice and deletes it.
32 func DeleteItem[T comparable](s []T, item T) []T {
33 index := slices.Index(s, item)
34 if index < 0 {
35 return s
36 }
37 return slices.Delete(s, index, index+1)
38 }