28 lines
588 B
TypeScript
28 lines
588 B
TypeScript
type BinaryDigit = 0 | 1
|
|
|
|
export interface Bit {
|
|
value: BinaryDigit
|
|
add: (other: Bit) => { ones: Bit, carry: Bit },
|
|
equals: (other: Bit) => boolean
|
|
}
|
|
|
|
export default function bit(value: BinaryDigit): Bit {
|
|
|
|
function add(other: Bit) {
|
|
const result = (value + other.value)
|
|
const ones = result % 2 as BinaryDigit
|
|
const carry = result === 2 ? 1 : 0
|
|
|
|
return { ones: bit(ones), carry: bit(carry) }
|
|
}
|
|
|
|
function equals(other: Bit) {
|
|
return value === other.value
|
|
}
|
|
|
|
return {
|
|
add,
|
|
value,
|
|
equals
|
|
}
|
|
} |