Last active
May 22, 2019 00:53
-
-
Save jbarrick-mesosphere/7fedb2c3359d683c58daa7749fae627d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package issubset | |
import "reflect" | |
// Check to see if `expected` is a subset of `actual`. A "subset" is an object that is equivalent to | |
// the other object, but where map keys found in actual that are not defined in expected are ignored. | |
func IsSubset(expected, actual interface{}) bool { | |
if reflect.TypeOf(expected) != reflect.TypeOf(actual) { | |
return false | |
} | |
if reflect.DeepEqual(expected, actual) { | |
return true | |
} | |
if reflect.TypeOf(expected).Kind() == reflect.Slice { | |
if reflect.ValueOf(expected).Len() != reflect.ValueOf(actual).Len() { | |
return false | |
} | |
for i := 0; i < reflect.ValueOf(expected).Len(); i++ { | |
if ! IsSubset(reflect.ValueOf(expected).Index(i).Interface(), reflect.ValueOf(actual).Index(i).Interface()) { | |
return false | |
} | |
} | |
} else if reflect.TypeOf(expected).Kind() == reflect.Map { | |
iter := reflect.ValueOf(expected).MapRange() | |
for iter.Next() { | |
actualValue := reflect.ValueOf(actual).MapIndex(iter.Key()) | |
if ! actualValue.IsValid() { | |
return false | |
} | |
if ! IsSubset(iter.Value().Interface(), actualValue.Interface()) { | |
return false | |
} | |
} | |
} else { | |
return false | |
} | |
return true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment