|
1 | 1 | package br.com.mob1st.core.kotlinx.structures
|
2 | 2 |
|
| 3 | +/** |
| 4 | + * BI-directional map, allowing searching by direct and reverse keys. |
| 5 | + * It's a simple wrapper on top of two maps, one for the left to right and another for the right to left. |
| 6 | + * @param L The type of the left key. |
| 7 | + * @param R The type of the right key. |
| 8 | + * @property leftToRight The map from left to right. |
| 9 | + * @property rightToLeft The map from right to left. |
| 10 | + */ |
3 | 11 | class BiMap<L, R>(
|
4 | 12 | private val leftToRight: MutableMap<L, R> = mutableMapOf(),
|
5 | 13 | private val rightToLeft: MutableMap<R, L> = mutableMapOf(),
|
6 | 14 | ) {
|
| 15 | + /** |
| 16 | + * Gets the right value from the left key. |
| 17 | + * @param left The left key or null if not found. |
| 18 | + */ |
7 | 19 | fun getLeft(left: L): R? = leftToRight[left]
|
8 | 20 |
|
| 21 | + /** |
| 22 | + * Gets the right value from the left key. |
| 23 | + * @param right The right key or null if not found. |
| 24 | + * @return The right value or null if not found. |
| 25 | + */ |
9 | 26 | fun getRight(right: R): L? = rightToLeft[right]
|
10 | 27 |
|
| 28 | + /** |
| 29 | + * Gets the right value from the left key, throwing an exception if not found. |
| 30 | + * @param left The left key. |
| 31 | + * @return The right value. |
| 32 | + * @throws NoSuchElementException If the left key is not found. |
| 33 | + */ |
11 | 34 | fun getLeftValue(left: L): R = leftToRight.getValue(left)
|
12 | 35 |
|
| 36 | + /** |
| 37 | + * Gets the right value from the left key, throwing an exception if not found. |
| 38 | + * @param right The right key. |
| 39 | + * @return The right value. |
| 40 | + * @throws NoSuchElementException If the right key is not found. |
| 41 | + */ |
13 | 42 | fun getRightValue(right: R): L = rightToLeft.getValue(right)
|
14 | 43 | }
|
15 | 44 |
|
| 45 | +/** |
| 46 | + * Creates a bi-directional map. |
| 47 | + * It uses the giben [pairs] of left and right values and both will be used as keys and values. |
| 48 | + * @param L The type of the left key. |
| 49 | + * @param R The type of the right key. |
| 50 | + * @param pairs The pairs of left and right values. |
| 51 | + * @return The bi-directional map. |
| 52 | + */ |
16 | 53 | fun <L, R> biMapOf(vararg pairs: Pair<L, R>): BiMap<L, R> {
|
17 | 54 | val leftToRight = mutableMapOf<L, R>()
|
18 | 55 | val rightToLeft = mutableMapOf<R, L>()
|
|
0 commit comments