Esempio n. 1
0
func Clone(c interface{}, cloned ...interface{}) (res interface{}) {
	cVal := reflect.ValueOf(c)

	switch cVal.Kind() {
	case reflect.Array:
		// arrays are passed by value...
		if len(cloned) > 0 {
			util.MapValues(cloned, c)
		}
		return c
	case reflect.Slice:
		dst := reflect.MakeSlice(cVal.Type(), cVal.Len(), cVal.Len())
		reflect.Copy(dst, cVal)
		res = dst.Interface()
	case reflect.Map:
		dst := reflect.MakeMap(cVal.Type())
		keys := cVal.MapKeys()
		for _, key := range keys {
			dst.SetMapIndex(key, cVal.MapIndex(key))
		}
		res = dst.Interface()
	default:
		mVal := cVal.MethodByName("Clone")
		if mVal.IsValid() && mVal.Type().NumIn() == 0 && mVal.Type().NumOut() == 1 {
			res = mVal.Call(nil)[0].Interface()
		}
	}

	if res != nil && len(cloned) > 0 {
		util.MapValues(cloned, res)
	}

	return res
}
Esempio n. 2
0
func Map(slice interface{}, f func(interface{}) interface{}, dest ...interface{}) (res interface{}) {
	var (
		sliceval = reflect.ValueOf(slice)
		lenslice = sliceval.Len()
	)

	if len(dest) > 0 && dest[0] != nil {
		newslice := fixSliceLen(reflect.Indirect(reflect.ValueOf(dest[0])), lenslice)

		for i := 0; i < lenslice; i++ {
			newslice.Index(i).Set(reflect.ValueOf(f(sliceval.Index(i).Interface())).Elem())
		}

		res = newslice.Interface()

		if len(dest) > 1 {
			util.MapValues(dest[1:], res)
		}
	} else {
		newslice := make([]interface{}, lenslice)

		for i := 0; i < lenslice; i++ {
			newslice[i] = f(sliceval.Index(i).Interface())
		}

		res = newslice
	}

	return
}
Esempio n. 3
0
func Filter(slice interface{}, f func(interface{}) bool, dest ...interface{}) (res interface{}) {
	var (
		sliceval = reflect.ValueOf(slice)
		lenslice = sliceval.Len()
		newslice = reflect.MakeSlice(sliceval.Type(), lenslice, lenslice)
		count    = 0
	)

	for i := 0; i < lenslice; i++ {
		val := sliceval.Index(i)
		if f(val.Interface()) {
			newslice.Index(count).Set(val)
			count++
		}
	}

	newslice.SetLen(count)
	res = newslice.Interface()
	util.MapValues(dest, res)

	return
}
Esempio n. 4
0
func Reduce(slice interface{}, f func(interface{}, interface{}) interface{}, init interface{}, dest ...interface{}) (res interface{}) {
	var (
		sliceval = reflect.ValueOf(slice)
		lenslice = sliceval.Len()
		i        = 0
	)

	if init != nil {
		res = init
	} else if lenslice > 0 {
		res = sliceval.Index(0)
		i = 1
	} else {
		return
	}

	for ; i < lenslice; i++ {
		res = f(res, sliceval.Index(i).Interface())
	}

	util.MapValues(dest, res)
	return
}