Adding Machine

node v10.24.1
version: 1.0.0
endpointsharetweet
// and or not const and = (a, b) => { switch (a) { case 0: switch (b) { case 0: return 0; case 1: return 0; } case 1: switch (b) { case 0: return 0; case 1: return 1; } } } const or = (a, b) => { switch (a) { case 0: switch (b) { case 0: return 0; case 1: return 1; } case 1: switch (b) { case 0: return 1; case 1: return 1; } } } const not = (a) => { switch (a) { case 0: return 1; case 1: return 0; } }
// nand nor xor const nand = (a, b) => (not(and(a, b))) const nor = (a, b) => (not(or(a, b))) const xor = (a, b) => (and(or(a, b), nand(a,b)))
const halfAdder = (a, b) => ({sum: xor(a, b), carry: and(a,b)}) const fullAdder = (a, b, carry) => { const result1 = halfAdder(a, b) const result2 = halfAdder((carry || 0), result1.sum) return {sum: result2.sum, carry: or(result1.carry, result2.carry)} } fullAdder(0, 1, 0)
const multiBitsSum = (inputA, inputB, carryIn) => { let output = [] let carry = carryIn || 0 for (var i = 0; i < inputA.length; i++) { let result = fullAdder(inputA[i], inputB[i], carry) output[i] = result.sum carry = result.carry } return {output: output, carry: carry} } multiBitsSum([0, 0, 1], [1, 1, 0]) const multiBitsSumByComp = (inputAHigh, inputBHigh, inputALow, inputBLow, carryIn) => { let output = [] let carry = carryIn || 0 const lowResult = multiBitsSum(inputALow, inputBLow, carry) const highResult = multiBitsSum(inputAHigh, inputBHigh, lowResult.carry) return {output: highResult.output.concat(highResult.output), carry: highResult.carry} } multiBitsSumByComp([0, 0, 1], [1, 1, 0], [0, 0, 1], [1, 1, 1])
Loading…

no comments

    sign in to comment