xgoprev/xmodules/enumx/main.go

70 lines
1.2 KiB
Go
Raw Normal View History

package enumx
import "github.com/d5/tengo/v2"
const src = `
_swap := func(arr, left, right) {
if arr == undefined || len(arr) <= 1 || left < 0 || left >= len(arr) || right < 0 || right >= len(arr) || left >= right {
return
}
temp := arr[right]
arr[right] = arr[left]
arr[left] = temp
}
_sort := func(arr, left, right, less) {
if arr == undefined || len(arr) <= 1 || left < 0 || left >= len(arr) || right < 0 || right >= len(arr) || left >= right {
return arr
}
idx := left
for i := left; i < right; i++ {
if less(arr[i], arr[right]) {
_swap(arr, idx, i)
idx++
}
}
_swap(arr, idx, right)
_sort(arr, left, idx-1, less)
_sort(arr, idx+1, right, less)
return arr
}
export {
keys: func(x){
ret := []
for k, _ in x {
ret += [k]
}
return ret
},
values: func(x){
ret := []
for _, v in x {
ret += [v]
}
return ret
},
sort: func(arr, ...less) {
if !less {
less = func(a, b){
return a < b
}
} else {
less = less[0]
}
if arr == undefined || len(arr) <= 1 {
return arr
}
return _sort(arr, 0, len(arr)-1, less)
}
}
`
func GetModule() tengo.Importable {
return &tengo.SourceModule{
Src: []byte(src),
}
}