Skip to content

Instantly share code, notes, and snippets.

@denk0403
Created March 23, 2023 03:59
Show Gist options
  • Save denk0403/a7da73d40032d63cc79d08967ecf275d to your computer and use it in GitHub Desktop.
Save denk0403/a7da73d40032d63cc79d08967ecf275d to your computer and use it in GitHub Desktop.
TypeScript Bijection
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