Skip to content

Instantly share code, notes, and snippets.

@jpmcglone
Created April 20, 2019 22:52
Show Gist options
  • Save jpmcglone/e3ff853e5f23e12d27a9b5da19e33cd3 to your computer and use it in GitHub Desktop.
Save jpmcglone/e3ff853e5f23e12d27a9b5da19e33cd3 to your computer and use it in GitHub Desktop.
import Foundation
public class BidirectionalMap<Left: Hashable, Right: Hashable> {
private var leftToRightMapping = [Left : Right]()
private var rightToLeftMapping = [Right : Left]()
public subscript(left: Left) -> Right? {
get { return leftToRightMapping[left] }
set (newValue) {
let oldRight = leftToRightMapping[left]
leftToRightMapping[left] = newValue
if let newValue = newValue {
rightToLeftMapping[newValue] = left
} else if let oldRight = oldRight {
rightToLeftMapping[oldRight] = nil
}
}
}
public subscript(right: Right) -> Left? {
get { return rightToLeftMapping[right] }
set (newValue) {
let oldLeft = rightToLeftMapping[right]
rightToLeftMapping[right] = newValue
if let newValue = newValue {
leftToRightMapping[newValue] = right
} else if let oldLeft = oldLeft {
leftToRightMapping[oldLeft] = nil
}
}
}
}
@jpmcglone
Copy link
Author

let map = BidirectionalMap = [Int: String]()

map[1] = "hello"

print(map["hello"]) // 1
print(map[1]) // "hello"

Both directions are O(1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment