Skip to content

Commit

Permalink
feat: add sort module to stdlib
Browse files Browse the repository at this point in the history
  • Loading branch information
huanghongkai committed Jun 1, 2023
1 parent 82b543f commit 6b92b0d
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
1 change: 1 addition & 0 deletions stdlib/source_modules.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

35 changes: 35 additions & 0 deletions stdlib/srcmod_sort.tengo
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
_sort := func(arr, left, right, less) {
if right-left <= 0 {
return
}
pivotIndex := 0
if right != pivotIndex {
tmp := arr[right]
arr[right] = arr[pivotIndex]
arr[pivotIndex] = tmp
}
for i := 0; i < len(arr); i++ {
if less(i, right) {
if i != left {
tmp := arr[i]
arr[i] = arr[left]
arr[left] = tmp
}
left = left + 1
}
}
if left != right {
tmp := arr[left]
arr[left] = arr[right]
arr[right] = tmp
}
_sort(arr, 0, left-1, less)
_sort(arr, left+1, right, less)
return arr
}

export {
sort: func(arr, less) {
return _sort(arr, 0, len(arr)-1, less)
}
}
11 changes: 11 additions & 0 deletions stdlib/stdlib_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,17 @@ if !is_error(cmd) {

}

func TestSortModule(t *testing.T) {
expect(t, `
sort := import("sort")
a := [4, 5, 3, 1, 2]
a = sort.sort(a, func(i, j) {
return a[i] < a[j]
})
out := import("json").encode(a)
`, []byte("[1,2,3,4,5]"))
}

func TestGetModules(t *testing.T) {
mods := stdlib.GetModuleMap()
require.Equal(t, 0, mods.Len())
Expand Down

0 comments on commit 6b92b0d

Please sign in to comment.