Last active
May 3, 2022 04:12
-
-
Save mizchi/ec510a28803483f6a07f200c44b93d6e 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
export type Point = { | |
t: 'point', | |
readonly x: number; | |
readonly y: number; | |
} | |
function get_distance(this: Point, other: Point) { | |
return Math.sqrt(Math.pow(this.x - other.x, 2) + Math.pow(this.y - other.y, 2)); | |
} | |
type Display<T> = { | |
display(t: T): string; | |
} | |
function display<T>(this: T, impl: Display<T>) { | |
return impl.display(this); | |
} | |
// usage | |
const display_for_point: Display<Point> = { | |
display(self: Point) { | |
return `(${self.x}, ${self.y})`; | |
} | |
} | |
const p1: Point = { t: 'point', x: 0, y: 0 } as const; | |
const p2: Point = { t: 'point', x: 3, y: 4 } as const; | |
const ret = get_distance.call(p1, p2); | |
console.log(ret); | |
console.log(display.call(p2, display_for_point)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment