Skip to content

Commit

Permalink
feat: few more helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
Tabaie committed Jan 22, 2022
1 parent bd03240 commit 63d5af2
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,18 +31,22 @@ func helpers() template.FuncMap {
// functions used in template
return template.FuncMap{
"add": add,
"bits": getBits,
"bytes": intBytes, //TODO: Do this directly
"capitalize": strings.Title,
"dict": dict,
"div": div,
"divides": divides,
"first": first,
"interval": interval,
"iterate": iterate,
"last": last,
"list": makeSlice,
"mod": mod,
"mul": mul,
"mul2": mul2,
"noFirst": noFirst,
"noLast": noLast,
"notNil": notNil,
"printList": printList,
"reverse": reverse,
Expand All @@ -53,6 +57,23 @@ func helpers() template.FuncMap {
}
}

func getBits(a interface{}) ([]bool, error) {

var res []bool
aI, err := toInt64(a)

if err != nil {
return res, err
}

for aI != 0 {
res = append(res, aI%2 != 0)
aI /= 2
}

return res, nil
}

func toInt64(a interface{}) (int64, error) {
switch i := a.(type) {
case uint8:
Expand Down Expand Up @@ -108,6 +129,17 @@ func assertSlice(input interface{}) (reflect.Value, error) {
return s, nil
}

func first(input interface{}) (interface{}, error) {
s, err := assertSlice(input)
if err != nil {
return nil, err
}
if s.Len() == 0 {
return nil, fmt.Errorf("empty slice")
}
return s.Index(0).Interface(), nil
}

func last(input interface{}) (interface{}, error) {
s, err := assertSlice(input)
if err != nil {
Expand Down Expand Up @@ -206,6 +238,39 @@ func reverse(input interface{}) interface{} {
}
return toReturn.Interface()
}

func noFirst(input interface{}) interface{} {
s, err := assertSlice(input)
if s.Len() == 0 {
return input
}
if err != nil {
return err
}
l := s.Len() - 1
toReturn := reflect.MakeSlice(s.Type(), l, l)
for i := 0; i < l; i++ {
toReturn.Index(i).Set(s.Index(i + 1))
}
return toReturn.Interface()
}

func noLast(input interface{}) interface{} {
s, err := assertSlice(input)
if s.Len() == 0 {
return input
}
if err != nil {
return err
}
l := s.Len() - 1
toReturn := reflect.MakeSlice(s.Type(), l, l)
for i := 0; i < l; i++ {
toReturn.Index(i).Set(s.Index(i))
}
return toReturn.Interface()
}

func add(a, b int) int {
return a + b
}
Expand Down

0 comments on commit 63d5af2

Please sign in to comment.