Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SortSlice, Sti and Its related #11

Closed
Aoi-hosizora opened this issue Jan 21, 2021 · 1 comment
Closed

SortSlice, Sti and Its related #11

Aoi-hosizora opened this issue Jan 21, 2021 · 1 comment

Comments

@Aoi-hosizora
Copy link
Owner

Aoi-hosizora commented Jan 21, 2021

type SortSlice struct {
	s    []interface{}
	less func(i, j int) bool
	swap func(i, j int)
}

func (s SortSlice) Len() int {
	return len(s.s)
}

func (s SortSlice) Less(i, j int) bool {
	return s.less(i, j)
}

func (s SortSlice) Swap(i, j int) {
	s.swap(i, j)
}

func NewSortSlice(s []interface{}, less func(i, j int) bool) SortSlice {
	return SortSlice{
		s:    s,
		less: less,
		swap: func(i, j int) { s[i], s[j] = s[j], s[i] },
	}
}

func ReverseSortSlice(s SortSlice) SortSlice {
	return SortSlice{
		s: s.s,
		less: func(i, j int) bool {
			return !s.less(i, j)
		},
		swap: s.swap,
	}
}

func Sort(s []interface{}, less func(i, j int) bool) {
	interfaceSlice := NewSortSlice(s, less)
	sort.Sort(interfaceSlice)
}

func StableSort(s []interface{}, less func(i, j int) bool) {
	interfaceSlice := NewSortSlice(s, less)
	sort.Stable(interfaceSlice)
}
func Sti(slice interface{}) []interface{} {
	if slice == nil {
		return nil
	}

	v := reflect.ValueOf(slice)
	if v.Type().Kind() != reflect.Slice {
		panic("Sti: parameter must be a slice")
	}

	l := v.Len()
	arr := make([]interface{}, l)
	for idx := 0; idx < l; idx++ {
		arr[idx] = v.Index(idx).Interface()
	}
	return arr
}

func Its(slice []interface{}, model interface{}) interface{} {
	if model == nil {
		panic("Its: model must be non-nil")
	}
	if slice == nil {
		return nil
	}

	t := reflect.TypeOf(model)
	l := len(slice)

	out := reflect.MakeSlice(reflect.SliceOf(t), l, l)
	for idx := range slice {
		v := reflect.ValueOf(slice[idx])
		out.Index(idx).Set(v)
	}
	return out.Interface()
}
@Aoi-hosizora Aoi-hosizora changed the title SortSlice related SortSlice, Sti and Its related Jan 21, 2021
@Aoi-hosizora
Copy link
Owner Author

Sort has been refactored to use innerSlice.

func coreSort(slice innerSlice, less Lesser, stable bool) {
	if less == nil {
		panic(nilLesserPanic)
	}
	ss := &sortSlice{slice: slice, less: less}
	if stable {
		sort.Stable(ss)
	} else {
		sort.Sort(ss)
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant