Skip to content

Instantly share code, notes, and snippets.

@JoshuaKGoldberg
Last active August 6, 2019 21:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshuaKGoldberg/81131c5a9e06160782ca5bb9f68b813a to your computer and use it in GitHub Desktop.
Save JoshuaKGoldberg/81131c5a9e06160782ca5bb9f68b813a to your computer and use it in GitHub Desktop.
Silly Binary Logic in TypeScript's Type System
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