Created
February 2, 2020 11:09
-
-
Save tonyfabeen/f659f9a7c09a8c2c5c7faaed8f99bc6e to your computer and use it in GitHub Desktop.
Dynamic Array in Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package array | |
const DefaultCapacity int = 10 | |
type Array struct { | |
capacity int | |
size int | |
items []interface{} | |
} | |
func DynamicArray() *Array { | |
items := make([]interface{}, DefaultCapacity) | |
return &Array{capacity: DefaultCapacity, items: items} | |
} | |
func (array *Array) Add(element interface{}) { | |
if array.size == array.capacity { | |
newCapacity := array.capacity * 2 | |
newArray := make([]interface{}, newCapacity) | |
for index, item := range array.items { | |
newArray[index] = item | |
} | |
array.capacity = newCapacity | |
array.items = newArray | |
} | |
array.items[array.size] = element | |
array.size++ | |
} | |
func (array *Array) Get(index int) interface{} { | |
return array.items[index] | |
} | |
func (array *Array) Size() int { | |
return array.size | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package array | |
import ( | |
"fmt" | |
"testing" | |
) | |
func TestDynamicArray(t *testing.T) { | |
array := DynamicArray() | |
t.Run("when a new array it returns a new Dynamic array", func(t *testing.T) { | |
if array == nil { | |
t.Errorf("should return an dynamic array") | |
} | |
}) | |
t.Run("when adding a new element to the Array", func(t *testing.T) { | |
array.Add(10) | |
if got := array.Size(); got != 1 { | |
t.Errorf("Size should be 1, but got %d", got) | |
} | |
array.Add(20) | |
if got := array.Size(); got != 2 { | |
t.Errorf("Size should be 2, but got %d", got) | |
} | |
if got := array.Get(0); got != 10 { | |
t.Errorf("should return the first added element %d", got) | |
} | |
if got := array.Get(1); got != 20 { | |
t.Errorf("should return the second added element %d", got) | |
} | |
}) | |
t.Run("when adding new element up to the capacity", func(t *testing.T) { | |
for index := 0; index < DefaultCapacity; index++ { | |
fmt.Printf("index %d, size %d\n", index, array.Size()) | |
array.Add(index) | |
} | |
if array.capacity != 20 { | |
t.Errorf("it should double the array capacity") | |
} | |
array.Add(99) | |
if got := array.Get(12); got != 99 { | |
t.Errorf("should be able to add items beyound previous capacity %d", got) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment