Created
April 14, 2019 21:18
-
-
Save dance2die/3f11e90723410431aae22f18fb4b0124 to your computer and use it in GitHub Desktop.
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
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