github.com/tursom/GoCollections@v0.3.10/collections/Collection.go (about) 1 /* 2 * Copyright (c) 2022 tursom. All rights reserved. 3 * Use of this source code is governed by a GPL-3 4 * license that can be found in the LICENSE file. 5 */ 6 7 package collections 8 9 import ( 10 "fmt" 11 "strings" 12 13 "github.com/tursom/GoCollections/exceptions" 14 "github.com/tursom/GoCollections/lang" 15 ) 16 17 type ( 18 Collection[E any] interface { 19 Iterable[E] 20 Size() int 21 IsEmpty() bool 22 Contains(element E) bool 23 ContainsAll(c Collection[E]) bool 24 } 25 26 MutableCollection[T any] interface { 27 Collection[T] 28 MutableIterable[T] 29 30 Add(element T) bool 31 Remove(element T) exceptions.Exception 32 AddAll(c Collection[T]) bool 33 RemoveAll(c Collection[T]) bool 34 RetainAll(c Collection[T]) bool 35 Clear() 36 } 37 38 List[T any] interface { 39 Collection[T] 40 41 Get(index int) (T, exceptions.Exception) 42 SubList(from, to int) List[T] 43 ListIterator() ListIterator[T] 44 } 45 46 MutableList[T any] interface { 47 List[T] 48 MutableCollection[T] 49 50 Set(index int, element T) exceptions.Exception 51 AddAtIndex(index int, element T) bool 52 RemoveAt(index int) exceptions.Exception 53 SubMutableList(from, to int) MutableList[T] 54 MutableListIterator() MutableListIterator[T] 55 } 56 ) 57 58 func ListGet[T lang.Object](list List[T], index int) T { 59 get, err := list.Get(index) 60 if err != nil { 61 panic(err) 62 } 63 return get 64 } 65 66 func ContainsAll[T lang.Object](l Collection[T], collection Collection[T]) bool { 67 return Loop[T](collection, func(e T) exceptions.Exception { 68 if l.Contains(e) { 69 return nil 70 } else { 71 return exceptions.ElementNotFound 72 } 73 }) == nil 74 } 75 76 func AddAll[T any](l MutableCollection[T], collection Collection[T]) bool { 77 return Loop[T](collection, func(e T) exceptions.Exception { 78 if !l.Add(e) { 79 return exceptions.CollectionLoopFinished 80 } 81 return nil 82 }) == nil 83 } 84 85 func String[T any](l Iterable[T]) string { 86 iterator := l.Iterator() 87 if !iterator.HasNext() { 88 return "[]" 89 } 90 91 builder := strings.Builder{} 92 builder.WriteString("[") 93 next, _ := iterator.Next() 94 builder.WriteString(fmt.Sprint(next)) 95 for iterator.HasNext() { 96 builder.WriteString(", ") 97 next, _ = iterator.Next() 98 builder.WriteString(fmt.Sprint(next)) 99 } 100 builder.WriteString("]") 101 return builder.String() 102 }