Skip to content

Instantly share code, notes, and snippets.

@dance2die dance2die/addBits.js
Created Apr 14, 2019

Embed
What would you like to do?
function addBits(v1, v2) {
const toNumberArray = str => str.split("").map(_ => +_);
const [a1, a2] = [toNumberArray(v1), toNumberArray(v2)];
// Add bits from right (least significant bit)
// to left (most significant bit)
const sum = a1.reduceRight((acc, a, i) => {
const b = a2[i];
// c => carry, s => sum
let [c, s] = [0, 0];
// Calculate the first bit
if (i === a1.length - 1) {
({ c, s } = halfAdder(a, b));
} else {
// Calculate the rest of the bits using the carry
const carry = (acc[0] && acc[0].c) || 0;
({ c, s } = fullAdder(a, b, carry));
}
return [{ c, s }, ...acc];
}, []);
// Build readable text
return sum.reduce(
(acc, { s, c }, i) => `${acc}${(i === 0 && c === 1 && "1") || ""}${s}`,
""
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.