-
Notifications
You must be signed in to change notification settings - Fork 11
/
FullAdder.js
69 lines (58 loc) · 1.56 KB
/
FullAdder.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* The MIT License (MIT)
* Copyright (c) 2017-present Dmitry Soshnikov <dmitry.soshnikov@gmail.com>
*/
'use strict';
const BuiltInGate = require('../BuiltInGate');
/**
* Canonical truth table for the `FullAdder` gate.
*/
const TRUTH_TABLE = [
{a: 0, b: 0, c: 0, sum: 0, carry: 0},
{a: 0, b: 0, c: 1, sum: 1, carry: 0},
{a: 0, b: 1, c: 0, sum: 1, carry: 0},
{a: 0, b: 1, c: 1, sum: 0, carry: 1},
{a: 1, b: 0, c: 0, sum: 1, carry: 0},
{a: 1, b: 0, c: 1, sum: 0, carry: 1},
{a: 1, b: 1, c: 0, sum: 0, carry: 1},
{a: 1, b: 1, c: 1, sum: 1, carry: 1},
];
/**
* A FullAdder.
*
* The `sum` returns the LSB of the sum of the three bits a, b and c.
* The `carry` returns the carry bit.
*/
class FullAdder extends BuiltInGate {
/**
* t = a + b + c
* sum = t % 2
* carry = t / 2
*/
eval() {
const a = this.getInputPins()[0].getValue();
const b = this.getInputPins()[1].getValue();
const c = this.getInputPins()[2].getValue();
const t = a + b + c;
this.getOutputPins()[0].setValue(t % 2); // sum
this.getOutputPins()[1].setValue(Math.trunc(t / 2)); // carry
}
}
/**
* Specification of the `FullAdder` gate.
*/
FullAdder.Spec = {
name: 'FullAdder',
description: [
'Implements 3-bits adder (full-adder) gate.',
'',
'The `sum` returns LSB (the least significant bit) of the sum',
'of the three bits `a`, `b` and `c`.',
'',
'The `carry` returns the carry bit.',
].join('\n'),
inputPins: ['a', 'b', 'c'],
outputPins: ['sum', 'carry'],
truthTable: TRUTH_TABLE,
};
module.exports = FullAdder;