Skip to content

Commit

Permalink
reducing complexity of newSlice
Browse files Browse the repository at this point in the history
  • Loading branch information
yazgazan committed Aug 20, 2019
1 parent 9801b52 commit a5f2827
Showing 1 changed file with 36 additions and 31 deletions.
67 changes: 36 additions & 31 deletions diff/slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,53 +119,58 @@ func newMyersSlice(c config, lhs, rhs interface{}, visited *visited) (Differ, er
}

func newSlice(c config, lhs, rhs interface{}, visited *visited) (Differ, error) {
var diffs []Differ
var indices []int
var (
diffs []Differ
indices []int
err error
typesDiffer bool
)

lhsVal := reflect.ValueOf(lhs)
rhsVal := reflect.ValueOf(rhs)

if typesDiffer, err := sliceTypesDiffer(lhs, rhs); err != nil {
if typesDiffer, err = sliceTypesDiffer(lhs, rhs); err != nil {
return slice{
lhs: lhs,
rhs: rhs,
}, err
} else if !typesDiffer {
nElems := lhsVal.Len()
if rhsVal.Len() > nElems {
nElems = rhsVal.Len()
}

for i := 0; i < nElems; i++ {
indices = append(indices, i)
if i < lhsVal.Len() && i < rhsVal.Len() {
diff, err := diff(c, lhsVal.Index(i).Interface(), rhsVal.Index(i).Interface(), visited)
diffs = append(diffs, diff)

if err != nil {
return slice{
lhs: lhs,
rhs: rhs,
diffs: diffs,
indices: indices,
}, err
}
continue
}
if i >= rhsVal.Len() {
diffs = append(diffs, sliceMissing{lhsVal.Index(i).Interface()})
continue
}
diffs = append(diffs, sliceExcess{rhsVal.Index(i).Interface()})
}
indices, diffs, err = sliceNewSameTypes(c, lhsVal, rhsVal, visited)
}

return slice{
lhs: lhs,
rhs: rhs,
diffs: diffs,
indices: indices,
}, nil
}, err
}

func sliceNewSameTypes(c config, lhsVal, rhsVal reflect.Value, visited *visited) (indices []int, diffs []Differ, err error) {
nElems := lhsVal.Len()
if rhsVal.Len() > nElems {
nElems = rhsVal.Len()
}

for i := 0; i < nElems; i++ {
indices = append(indices, i)
if i < lhsVal.Len() && i < rhsVal.Len() {
diff, err := diff(c, lhsVal.Index(i).Interface(), rhsVal.Index(i).Interface(), visited)
diffs = append(diffs, diff)

if err != nil {
return indices, diffs, err
}
continue
}
if i >= rhsVal.Len() {
diffs = append(diffs, sliceMissing{lhsVal.Index(i).Interface()})
continue
}
diffs = append(diffs, sliceExcess{rhsVal.Index(i).Interface()})
}

return indices, diffs, nil
}

func sliceTypesDiffer(lhs, rhs interface{}) (bool, error) {
Expand Down

0 comments on commit a5f2827

Please # to comment.