Skip to content

Commit 9a867e5

Browse files
committed
Reducing diff() complexity
1 parent f04869f commit 9a867e5

File tree

2 files changed

+15
-6
lines changed

2 files changed

+15
-6
lines changed

diff/diff.go

+14-5
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,8 @@ func diff(lhs, rhs interface{}, visited *visited) (Differ, error) {
4141
lhsVal := reflect.ValueOf(lhs)
4242
rhsVal := reflect.ValueOf(rhs)
4343

44-
if lhs == nil && rhs == nil {
45-
return scalar{lhs, rhs}, nil
46-
}
47-
if lhs == nil || rhs == nil {
48-
return types{lhs, rhs}, nil
44+
if d, ok := nilCheck(lhs, rhs); ok {
45+
return d, nil
4946
}
5047
if err := visited.add(lhsVal, rhsVal); err != nil {
5148
return types{lhs, rhs}, ErrCyclic
@@ -56,6 +53,7 @@ func diff(lhs, rhs interface{}, visited *visited) (Differ, error) {
5653
if lhsVal.Kind() != rhsVal.Kind() {
5754
return types{lhs, rhs}, nil
5855
}
56+
5957
if lhsVal.Kind() == reflect.Slice {
6058
return newSlice(lhs, rhs, visited)
6159
}
@@ -66,6 +64,17 @@ func diff(lhs, rhs interface{}, visited *visited) (Differ, error) {
6664
return types{lhs, rhs}, &ErrUnsupported{lhsVal.Type(), rhsVal.Type()}
6765
}
6866

67+
func nilCheck(lhs, rhs interface{}) (Differ, bool) {
68+
if lhs == nil && rhs == nil {
69+
return scalar{lhs, rhs}, true
70+
}
71+
if lhs == nil || rhs == nil {
72+
return types{lhs, rhs}, true
73+
}
74+
75+
return nil, false
76+
}
77+
6978
func (t Type) String() string {
7079
switch t {
7180
case Identical:

diff/map.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ type mapExcess struct {
2121
value interface{}
2222
}
2323

24-
func newMap(lhs, rhs interface{}, visited *visited) (mapDiff, error) {
24+
func newMap(lhs, rhs interface{}, visited *visited) (Differ, error) {
2525
var diffs = make(map[interface{}]Differ)
2626

2727
lhsVal := reflect.ValueOf(lhs)

0 commit comments

Comments
 (0)