Created
March 23, 2023 03:59
-
-
Save denk0403/a7da73d40032d63cc79d08967ecf275d to your computer and use it in GitHub Desktop.
TypeScript Bijection
This file contains hidden or 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
class Bijection<T, U> { | |
static FORWARD = 0 as const; | |
static BACKWARD = 1 as const; | |
#maps = [new Map<T, U>(), new Map<U, T>()] as const; | |
set(forwardVal: T, backwardVal: U) { | |
this.#maps[0].set(forwardVal, backwardVal); | |
this.#maps[1].set(backwardVal, forwardVal); | |
} | |
get<Direction extends typeof Bijection.FORWARD | typeof Bijection.BACKWARD>( | |
direction: Direction, | |
value: Direction extends typeof Bijection.FORWARD ? T : U | |
): (Direction extends typeof Bijection.FORWARD ? U : T) | undefined { | |
// @ts-ignore | |
return this.#maps[direction].get(value); | |
} | |
} | |
// Example: | |
let numStrBijection = new Bijection<number, string>(); | |
numStrBijection.set(4, "4") | |
numStrBijection.set(100, "100") | |
let result1 = numStrBijection.get(Bijection.FORWARD, 4) | |
let result2 = numStrBijection.get(Bijection.BACKWARD, "4") | |
let result3 = numStrBijection.get(Bijection.FORWARD, "4") // type error | |
let result4 = numStrBijection.get(Bijection.BACKWARD, 4) // type error | |
let result5 = numStrBijection.get(3, 4) // type error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment