Search code examples
javascriptalgorithmtesting

Checking odds and evens


I do not understand this question.

I create a function or callable object that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers. The function should also return "Even" or "Odd" when accessing a value at an integer index. This part is somewhat confusing because we are not accessing an array or passing an array through the function. My function is as follows:

function evenOrOdd(n) {
  //'Even' or 'Odd'
  if(n==0){
    return 'Even';
  }else if(n%2==0){
    return 'Even';
  }
  else{
    return 'Odd';
  }
}

But then tests are like this:

const chai = require('chai');
const assert = chai.assert;

describe("Sample tests",() => {
  
  it("[4] is even", () => {
    assert.strictEqual(evenOrOdd[4], "Even"); //<--- How do I solv this? Test Fails
  });
  it("2 is even", () => {
    assert.strictEqual(evenOrOdd(2), "Even"); //<--- Test Passd as expected
  });
  it("[11] is odd", () => {
    assert.strictEqual(evenOrOdd[11], "Odd"); //<--- How do I solv this? Test Fails
  });
  it("7 is odd", () => {
    assert.strictEqual(evenOrOdd(7), "Odd"); // Test Passd as expected
  });
  
});

What am I not understanding here and how do I overcome this?


Solution

  • You can't call a function with square brackets; if you want to do that (I'm not sure why, but I'm sure this question is for some bigger picture), then you need to create a Proxy object to act as a proxy to your evenOrOdd function.

    Something along the lines of this:

    function evenOrOdd(n) {
      if (n % 2 === 0) {
        return 'Even';
      } else {
        return 'Odd';
      }
    }
    
    const evenOrOddProxy = new Proxy(evenOrOdd, {
      get: function(target, prop) {
        if (!isNaN(prop)) {
          return evenOrOdd(Number(prop));
        }
        return target[prop];
      }
    });
    
    // Tests
    console.log('Tests:')
    console.log(evenOrOddProxy[4] === "Even")  // <-- true
    console.log(evenOrOddProxy(2) === "Even")  // <-- true
    console.log(evenOrOddProxy[11] === "Odd")  // <-- true
    console.log(evenOrOddProxy(7) === "Odd")   // <-- true

    1. Wrap the function in a Proxy object
    2. Use a get trap in the Proxy to intercept property accesses. When a numeric property (e.g., 4 or 11) is accessed, it calls the evenOrOdd function with that number.

    This allows both function calls with parentheses and property accesses with square brackets.