Created
April 20, 2019 22:52
-
-
Save jpmcglone/e3ff853e5f23e12d27a9b5da19e33cd3 to your computer and use it in GitHub Desktop.
This file contains 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
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 | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Both directions are O(1)