Hashable structured data
Would it be possible to implement a Hashable extension to StructuredData ?
I see we already provide an implementation for equals, so this would be a nice addition, as it would save me from unwrapping the structured data type.
Here is my idea.
extension StructuredDataWrapper {
var hashValue: Int {
switch self.wrapped {
case let .bool(bool):
return bool.hashValue
case let .number(number):
switch number {
case let .int(int):
return int.hashValue
case let .double(double):
return double.hashValue
case let .uint(uint):
return uint.hashValue
}
case let .string(string):
return string.hashValue
case let .date(date):
return date.hashValue
case let .bytes(bytes):
return bytes.makeString().hashValue
case let .array(array):
// Not too sure here
return 0
case let .object(object):
// Not too sure here
return 0
case .null:
return 0
}
}
}
For arrays and objects, you could do something like:
array.reduce(0) { acc, item in 31 * acc + item.hashValue }
(Also, infinite +1s to the idea. This is a trivial extension of the whole StructuredData context.)
@vzsg what does 31 mean?
It's a magic number (an odd prime) that often appears in other hash implementations. I heard about it in a university lecture years ago, so my memory is a little blurry, but IIRC using that as a multiplier reduces the chance of collisions.
🙌 math. I like this idea. @hhanesand wanna take a stab at implementing? Looks like you already have most of it here.
@tanner0101 sure :)