Search code examples
javascriptchaining

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.


Solution

  • 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