aboutsummaryrefslogtreecommitdiffstats
path: root/client/go/internal/util/array_list.go
blob: 2e74d30fcec921db301306bb0dede8f4c4755f3c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
// Author: arnej

// generic utilities
package util

type ArrayList[E comparable] []E

func NewArrayList[E comparable](initialCapacity int) ArrayList[E] {
	return make([]E, 0, initialCapacity)
}

func ArrayListOf[E comparable](elems []E) ArrayList[E] {
	return ArrayList[E](elems)
}

func (arrayP *ArrayList[E]) Append(elem E) {
	*arrayP = append(*arrayP, elem)
}

func (arrayP *ArrayList[E]) AppendAll(elemsToAppend ...E) {
	firstLen := len(*arrayP)
	secondLen := len(elemsToAppend)
	totLen := firstLen + secondLen
	if totLen > cap(*arrayP) {
		res := make([]E, totLen, cap(*arrayP)+cap(elemsToAppend))
		copy(res, *arrayP)
		copy(res[firstLen:], elemsToAppend)
		*arrayP = res
	} else {
		res := (*arrayP)[0:totLen]
		copy(res[firstLen:], elemsToAppend)
		*arrayP = res
	}
}

func (arrayP *ArrayList[E]) Insert(index int, elem E) {
	cur := *arrayP
	oldLen := len(cur)
	result := append(cur, elem)
	if index != oldLen {
		copy(result[index+1:], cur[index:])
		result[index] = elem
	}
	*arrayP = result
}

func (arrayP *ArrayList[E]) InsertAll(index int, elemsToInsert ...E) {
	firstLen := len(*arrayP)
	secondLen := len(elemsToInsert)
	totLen := firstLen + secondLen
	var res []E
	if totLen > cap(*arrayP) {
		res = make([]E, totLen, cap(*arrayP)+cap(elemsToInsert))
		firstPart := (*arrayP)[:index]
		copy(res, firstPart)
	} else {
		res = (*arrayP)[0:totLen]
	}
	thirdPart := (*arrayP)[index:]
	dst := res[index+secondLen:]
	copy(dst, thirdPart)
	dst = res[index:]
	copy(dst, elemsToInsert)
	*arrayP = res
}

func (arrayP *ArrayList[E]) Contains(elem E) bool {
	for _, old := range *arrayP {
		if elem == old {
			return true
		}
	}
	return false
}

func (arrayP *ArrayList[E]) Each(f func(E)) {
	for _, elem := range *arrayP {
		f(elem)
	}
}