Skip to content

Commit

Permalink
VM now supports custom sort functions
Browse files Browse the repository at this point in the history
Added sort SortFuncsStruct
  • Loading branch information
MichaelS11 committed Mar 7, 2018
1 parent 9a3cce4 commit 44d38af
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
17 changes: 14 additions & 3 deletions packages/sort.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@ import (
"sort"
)

type SortFuncsStruct struct {
LenFunc func() int
LessFunc func(i, j int) bool
SwapFunc func(i, j int)
}

func (s SortFuncsStruct) Len() int { return s.LenFunc() }
func (s SortFuncsStruct) Less(i, j int) bool { return s.LessFunc(i, j) }
func (s SortFuncsStruct) Swap(i, j int) { s.SwapFunc(i, j) }

func init() {
Packages["sort"] = map[string]interface{}{
"Float64s": sort.Float64s,
Expand All @@ -21,9 +31,10 @@ func init() {
"StringsAreSorted": sort.StringsAreSorted,
}
PackageTypes["sort"] = map[string]interface{}{
"Float64Slice": sort.Float64Slice{},
"IntSlice": sort.IntSlice{},
"StringSlice": sort.StringSlice{},
"Float64Slice": sort.Float64Slice{},
"IntSlice": sort.IntSlice{},
"StringSlice": sort.StringSlice{},
"SortFuncsStruct": &SortFuncsStruct{},
}
sortGo18()
}
11 changes: 11 additions & 0 deletions packages/sort_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,17 @@ func TestSort(t *testing.T) {
{script: "sort = import(\"sort\"); a = make([]\"int\"); a += [5, 3, 1, 4, 2]; sort.Ints(a); a", runOutput: []int{1, 2, 3, 4, 5}, output: map[string]interface{}{"a": []int{1, 2, 3, 4, 5}}},
{script: "sort = import(\"sort\"); a = make([]\"float64\"); a += [5.5, 3.3, 1.1, 4.4, 2.2]; sort.Float64s(a); a", runOutput: []float64{1.1, 2.2, 3.3, 4.4, 5.5}, output: map[string]interface{}{"a": []float64{1.1, 2.2, 3.3, 4.4, 5.5}}},
{script: "sort = import(\"sort\"); a = make([]\"string\"); a += [\"e\", \"c\", \"a\", \"d\", \"b\"]; sort.Strings(a); a", runOutput: []string{"a", "b", "c", "d", "e"}, output: map[string]interface{}{"a": []string{"a", "b", "c", "d", "e"}}},
{script: `
sort = import("sort")
a = [5, 1.1, 3, "f", "2", "4.4"]
sortFuncs = make("sort.SortFuncsStruct")
sortFuncs.LenFunc = func() { return len(a) }
sortFuncs.LessFunc = func(i, j) { return a[i] < a[j] }
sortFuncs.SwapFunc = func(i, j) { temp = a[i]; a[i] = a[j]; a[j] = temp }
sort.Sort(sortFuncs)
a
`,
runOutput: []interface{}{"f", float64(1.1), "2", int64(3), "4.4", int64(5)}, output: map[string]interface{}{"a": []interface{}{"f", float64(1.1), "2", int64(3), "4.4", int64(5)}}},
}
runTests(t, tests)
}

0 comments on commit 44d38af

Please sign in to comment.