Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS chaining functions

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.

like image 971
sinnerwithguts Avatar asked Dec 22 '22 20:12

sinnerwithguts


2 Answers

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
like image 84
Chris Li Avatar answered Dec 28 '22 23:12

Chris Li


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

like image 45
Paulo Künzel Avatar answered Dec 28 '22 23:12

Paulo Künzel