Last active
August 6, 2019 21:51
-
-
Save JoshuaKGoldberg/81131c5a9e06160782ca5bb9f68b813a to your computer and use it in GitHub Desktop.
Silly Binary Logic in TypeScript's Type System
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
type Bit = 0 | 1; | |
type BitFlip<A> = A extends 0 | |
? 1 | |
: 0; | |
type BitOr<A, B> = [A, B] extends [0, 0] | |
? 0 | |
: 1; | |
type BitAnd<A, B> = [A, B] extends [1, 1] | |
? 1 | |
: 0; | |
type BitXor<A, B> = [A, B] extends [0, 0] | [1, 1] | |
? 1 | |
: 0; | |
// Output: [Xor, Carry] | |
type BitAdd<A, B> = [BitXor<A, B>, BitAnd<A, B>]; | |
// This snippet doesn't take care of all the edge cases, but doing so is kind of unreadable at first... | |
// See https://gist.github.com/JoshuaKGoldberg/7543c2b3258fdce0a4ad70fd854ff7ff for the full thing. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment