node icon indicating copy to clipboard operation
node copied to clipboard

Hashable structured data

Open hhanesand opened this issue 8 years ago • 5 comments

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
        }
    }
}

hhanesand avatar Jun 10 '17 20:06 hhanesand

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 avatar Jun 10 '17 21:06 vzsg

@vzsg what does 31 mean?

tanner0101 avatar Jun 14 '17 16:06 tanner0101

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.

vzsg avatar Jun 14 '17 16:06 vzsg

🙌 math. I like this idea. @hhanesand wanna take a stab at implementing? Looks like you already have most of it here.

tanner0101 avatar Jun 14 '17 16:06 tanner0101

@tanner0101 sure :)

hhanesand avatar Jun 14 '17 22:06 hhanesand