-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathKeyable.swift
50 lines (29 loc) · 1002 Bytes
/
Keyable.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//
// Keyable.swift
// SwiftStructures
//
// Created by Wayne Bishop on 10/10/17.
// Copyright © 2017 Arbutus Software Inc. All rights reserved.
//
import Foundation
//note: an extension on a protocol
extension Keyable {
//compute table index
func hashValue<T>(for key: String!, using buckets: Array<T>) -> Int {
var remainder: Int = 0
var divisor: Int = 0
//trivial case
guard key != nil else {
return -1
}
for item in key.unicodeScalars {
divisor += Int(item.value)
}
/*
note: modular math is used to calculate a hash value. The bucket count is used
as the dividend to ensure all possible outcomes are between 0 and the collection size.
*/
remainder = divisor % buckets.count
return remainder
}
}