Published
Edited
Oct 16, 2018
5 stars
Insert cell
Insert cell
Insert cell
add(96, 128)
Insert cell
Insert cell
subtract(32, 12)
Insert cell
Insert cell
function halfAdder(a, b) {
const sum = (a | b) & ~(a & b); // xor
const carry = a & b;
return [sum, carry];
}
Insert cell
Insert cell
function fullAdder(a, b, carry) {
const [sum1, carry1] = halfAdder(a, b);
const [sum2, carry2] = halfAdder(sum1, carry);
return [sum2, carry1 || carry2];
}
Insert cell
Insert cell
calculator = ({ add: bitAdd, subtract: bitSubtract })
Insert cell
function bitAdd() {
let sum = 0, carry = 0;
return function (a, b) {
[sum, carry] = fullAdder(a, b, carry);
return sum;
}
}
Insert cell
function bitSubtract() {
let sum = 0, carry = 1;
return function (a, b) {
[sum, carry] = fullAdder(a, ~b & 1, carry);
return sum;
}
}
Insert cell
function calculate(a, b, mode) {
const bitsA = getBits(a);
const bitsB = getBits(b);
const calculate = calculator[mode]();
let result = 0;
let count = 0;
let A, B;
do {
A = bitsA.next();
B = bitsB.next();
result += calculate(A.value, B.value) << count;
count += 1;
} while (!(A.done && B.done));
return result;
}
Insert cell
getBits = function* (int) {
while (int > 0) {
yield int & 1;
int >>= 1;
}
}
Insert cell
add = function(a, b) {
return calculate(a, b, 'add');
}
Insert cell
subtract = function(a, b) {
return calculate(a, b, 'subtract');
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more