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

Slices should append not overwrite #45

Merged
merged 1 commit into from
Jan 11, 2018
Merged

Conversation

the4thamigo-uk
Copy link

@the4thamigo-uk the4thamigo-uk commented Oct 16, 2017

Proposed fix to cause slices to be appended to, rather than replaced. Also noticed that maps of slices don't seem to be working, so added unit tests for that as well.

fixes #35

@tzapu
Copy link

tzapu commented Feb 10, 2018

This is a wonderful feature to have included, thank you.

One question, would it not be more intuitive to append only if it’s not contained in the slice?

If you just want to update an object, you will get duplicates currently.

Cheers

@darccio
Copy link
Owner

darccio commented Apr 2, 2018

@tzapu, this was already merged on January. About your question, what if we really want to merge all values, no matter what? Also, this is coherent with slices way of work, as appending to a slice doesn't look if the value already exists. Maps "append" checking by key and overwriting the existing value if key exists.

You can implement a Transformer to handle your case.

@tzapu
Copy link

tzapu commented Apr 3, 2018

hi, thanks, that's actually the route i went down on

package tripleutil

import (
	"reflect"
)

type SliceMerger struct {
}

func (am SliceMerger) Transformer(typ reflect.Type) func(dst, src reflect.Value) error {
	if typ.Kind() == reflect.Slice {
		return func(dst, src reflect.Value) error {

		next:
			for i := 0; i < src.Len(); i++ {
				for j := 0; j < dst.Len(); j++ {
					// not adding elements already found
					if reflect.DeepEqual(src.Index(i).Interface(), dst.Index(j).Interface()) {
						continue next
					}
				}
				// else we append it to destination
				dst.Set(reflect.Append(dst, src.Index(i)))
			}
			return nil
		}
	}
	return nil
}

if anyone else might need such a thing

thank you for this lovely piece of work :D

/edit: the above only works for merge, not merge with overwrite

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

Successfully merging this pull request may close these issues.

Slice and Maps are handled differently
4 participants