4

I'm writing a function that should work like this:

checker(3).equals(3) // true
checker(3).not().equals(3) // false
checker(3).not().equals(4) // true
checker(3).not().not().equals(4) // false

The code I came up with:

function checker(num) {
  let number = num
  return {
    not() {
      number = !number
      return this
    },
    equals(nmb) {
      return number === nmb
    }
  }
}

I can't wrap my head around what should not() do so as to make checker(num) work as it is supposed to.

4 Answers 4

4

You can add another boolean property that changes how equals works depending on it's value.

function checker(num) {
  let number = num
  let not = false
  return {
    not() {
      not = !not
      return this
    },
    equals(nmb) {
      return not ? number !== nmb : number === nmb
    }
  }
}

console.log(checker(3).equals(3)) // true
console.log(checker(3).not().equals(3)) // false
console.log(checker(3).not().equals(4)) // true
console.log(checker(3).not().not().equals(4)) // false

Sign up to request clarification or add additional context in comments.

1 Comment

You could replace not ? number !== nmb : number === nmb with (number === nmb) !== not
3

Maybe somthing like this:

function checker(num) {
  let number = num
  let beTrue = true;
  return {
    not() {
      beTrue = !beTrue;
      return this
    },
    equals(nmb) {
      return (number === nmb) === beTrue;
    }
  }
}

It seems to fullfil your requirements. Hope it helps

Comments

2

An ES6 approach

const checker=(number, negate)=>{
    const neg = negate || false;
  return {
    not(){
        return checker(number, !neg);
    }, 
    equals(number2){
        if (neg) return number != number2;
      return number == number2;
    }
  }
}

what should not() do so as to make checker(num) work as it is supposed to.

not could return a new checker.

Comments

1

I think i would let the notfunction control the operator, something like

function checker(num) {
  let operator = 'equals'; 
  let number = num
  return {
    not() {
      if(operator==='equals')    
         operator = 'not equals'; 
      else 
          operator = 'equals'; 
      return this
    },
    equals(nmb) {
      if(operator==='equals')  
         return number === nmb
      else 
        return number !== nmb
    }
  }
}

just using a string as operator for clarity, a proberly better solution could be to use a boolean or number value

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.