/
Sort.go
64 lines (57 loc) · 1.52 KB
/
Sort.go
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
// =================================================================
//
// Copyright (C) 2019 Spatial Current, Inc. - All Rights Reserved
// Released as open source under the MIT License. See LICENSE file.
//
// =================================================================
package af
import (
"reflect"
"sort"
)
func sortArray(args ...interface{}) (interface{}, error) {
descending := false
if len(args) > 1 {
switch args[1].(type) {
case bool:
descending = args[1].(bool)
default:
return nil, &ErrInvalidArguments{Function: "Sort", Arguments: args}
}
}
switch arr := args[0].(type) {
case []string:
if descending {
sort.Sort(sort.Reverse(sort.StringSlice(arr)))
} else {
sort.Strings(arr)
}
return arr, nil
case []int:
if descending {
sort.Sort(sort.Reverse(sort.IntSlice(arr)))
} else {
sort.Ints(arr)
}
return arr, nil
case []float64:
if descending {
sort.Sort(sort.Reverse(sort.Float64Slice(arr)))
} else {
sort.Float64s(arr)
}
return arr, nil
}
return nil, &ErrInvalidArguments{Function: "Sort", Arguments: args}
}
var Sort = Function{
Name: "Sort",
Aliases: []string{"sort"},
Definitions: []Definition{
Definition{Inputs: []interface{}{stringSliceType}, Output: stringSliceType},
Definition{Inputs: []interface{}{intSliceType}, Output: intSliceType},
Definition{Inputs: []interface{}{stringSliceType, reflect.Bool}, Output: stringSliceType},
Definition{Inputs: []interface{}{intSliceType, reflect.Bool}, Output: intSliceType},
},
Function: sortArray,
}