-
Notifications
You must be signed in to change notification settings - Fork 47
01. Week 1 Exercise
Tran Phong Phu edited this page Jul 19, 2019
·
2 revisions
We will consider to porting Underscore in Javascript language to Go language
Some features such as IsEmpty
, Last
... are missed in Go so we will try first
We can consider some of case:
-
slice
,map
withlen
is zero -
string
is""
-
boolean
is false -
number
is 0 - ...
So the simplest code could implemented is:
func IsEmpty(obj interface{}) bool {
if obj == nil || obj == "" || obj == false || obj == 0 {
return true
}
return false
}
func TestIsEmpty(t *testing.T) {
table := []interface{}{false, "", 0, nil}
for _, v := range table {
expected := IsEmpty(v)
if expected != true {
t.Error("IsEmpty of \"", v, "\" is failed.")
}
}
}
More stricks of slice you can follow here
For just reading the last element of a slice:
sl[len(sl)-1]
So we really don't need to reinvent the wheel for this, but in other way to think about readable code, we could consider this function
func Last(arr interface{}) interface{} {
value := reflect.ValueOf(arr)
return value.Index(value.Len() - 1).Interface()
}
func TestLast(t *testing.T) {
arr := []int{1, 2, 3}
v := Last(arr)
var expected int
expected = 3
if v != expected {
t.Error("Value should be ", expected)
}
}
ⓒ 2019 Phú, Trần Phong & NordicCoder