Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS - stop objects chaining without error

Tags:

javascript

oop

I've got array of objects like chessboard, each of them has top, down, left, right function that returns object neighbour.

data.field(3,3).left() //returns field(2,3);

I can chain it like

data.field(3,3).left().left().top().right().down().getName();

But there is no object with negative cords like

data.field(-1,0)

Its easy to detect when given cords are negative or bigger than objects array. You can return false or empty object - but when there is nothing returned and chaining is continued there is an error

Uncaught TypeError: Object #<error> has no method 'down'

Which is ofc thing, but how can I avoid this error, and stop the long chain when there is no object to return without getting error that stops js executing?

Lets say:

data.left().left()/*here there is nothing to return*/.right().right().getName(); //should return false
like image 553
OPOPO Avatar asked Mar 21 '26 03:03

OPOPO


1 Answers

Instead of returning null for an invalid location, return a custom "null object" that overrides the directional functions to just return a null object with a getName function that returns "invalid location" , or throws an exception when those functions are called.

nullObject = {

    this.left = function(){return this;}
    this.right =  function(){return this;}
    //etc
    this.getName = function(){"Invalid Location"}

}

The exception handling could look like this

try{
  piece.left().right().down().getName()
}
catch(exc){
  //handle exception
}

Incidentally, you're essentially creating a monad here. If you have it stop the computation when it receives the null object, then thats an example of the maybe monad. Thats a few theoretical levels above the practical concern here though.

like image 50
Ben McCormick Avatar answered Mar 23 '26 16:03

Ben McCormick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!