0

I have a class performing some simple logic operations such as NAND. Internally other functions build on NAND such that AND is made from two NANDs.

class Logic {
    constructor(a,b) {
        this.a = a;
        this.b = b;
    }

    NAND(a,b) {
        return !(a && b); 
    }

    OR(a,b) {
       return this.NAND(this.NAND(a,a),this.NAND(b,b)); 
    }
}

In my unit test I want to make sure that this works and there is no problem:

describe('Testing the OR method', function() {
    it('OR 0,0 should return 0', function() {
        let o = logic.OR(0,0);
        assert.equal(o,0);
    });
    it('OR 0,1 should return 1', function() {
        let o = logic.OR(0,1);
        assert.equal(o,true);
    });
    it('OR 1,0 should return 0', function() {
        let o = logic.OR(1,0);
        assert.equal(o,true);
    });
    it('OR 1,1 should return 0', function() {
        let o = logic.OR(1,1);
        assert.equal(o,true);
    });
});  

However, when adding a function to my class which I would like to use later on for tests, it fails.

getFunction(which) {
    switch(which.toLowerCase()) {
        case '&&':
        case 'and':
        case '^':   return this.AND;
        case '!&&':
        case 'nand':
        case '!^':  return this.NAND;
        case '||':
        case 'or':
        case 'v':   return this.OR;
        case '!':
        case 'not': return this.NOT;
        default:    return null;
   }
}

In the test this fails:

describe('Testing function retrieval', function() {
    it('Should return the AND function', function() {
        let f = logic.getFunction('^');
        assert.equal(f.name,'AND');
        console.log(f(1,1));
    });
});   

the assertion actually evaluates to true, but executing the function fails with:

TypeError: Cannot read property 'NAND' of undefined

Any idea what is wrong here?

jallmer
  • 589
  • 3
  • 17
  • 1
    Your code breaks the relationship of the logic functions to the instance. – Pointy Apr 14 '19 at 15:34
  • `return this.AND.bind(this);` (etc) would fix it, because it would return functions permanently bound to the instance. – Pointy Apr 14 '19 at 15:35
  • Alternatively, `return (a, b) => this.AND(a, b)` since you know it will always accept two arguments. – Patrick Roberts Apr 14 '19 at 15:36
  • Both change the resulting name of the function to 'bound and' and '', respectively. Any chance to keep the name intact? – jallmer Apr 14 '19 at 15:48

0 Answers0