Skip to content

Commit

Permalink
Add Tail and Initial implementations (closes #23 and #17)
Browse files Browse the repository at this point in the history
  • Loading branch information
thoas committed Jan 13, 2017
1 parent 6affea2 commit ff444e7
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
40 changes: 40 additions & 0 deletions scan.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,43 @@ func Last(arr interface{}) interface{} {

panic(fmt.Sprintf("Type %s is not supported by Last", valueType.String()))
}

// Initial gets all but the last element of array.
func Initial(arr interface{}) interface{} {
value := redirectValue(reflect.ValueOf(arr))
valueType := value.Type()

kind := value.Kind()

if kind == reflect.Array || kind == reflect.Slice {
length := value.Len()

if length <= 1 {
return arr
}

return value.Slice(0, length-1).Interface()
}

panic(fmt.Sprintf("Type %s is not supported by Initial", valueType.String()))
}

// Tail gets all but the last element of array.
func Tail(arr interface{}) interface{} {
value := redirectValue(reflect.ValueOf(arr))
valueType := value.Type()

kind := value.Kind()

if kind == reflect.Array || kind == reflect.Slice {
length := value.Len()

if length <= 1 {
return arr
}

return value.Slice(1, length).Interface()
}

panic(fmt.Sprintf("Type %s is not supported by Initial", valueType.String()))
}
12 changes: 12 additions & 0 deletions scan_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,15 @@ func TestLast(t *testing.T) {

is.Equal(Last([]int{1, 2, 3, 4}), 4)
}

func TestTail(t *testing.T) {
is := assert.New(t)

is.Equal(Tail([]int{1, 2, 3, 4}), []int{2, 3, 4})
}

func TestInitial(t *testing.T) {
is := assert.New(t)

is.Equal(Initial([]int{1, 2, 3, 4}), []int{1, 2, 3})
}

0 comments on commit ff444e7

Please sign in to comment.