dimanche 20 août 2017

clean code: nested if

this question was probably answered before.

But how would you improve this bit of code?

I have a function that takes parameters x and y and compares them to an object

{point: {x: ..., y: ,,,}, nodes: [null]}

and the nodes are either

[null] or [object, object, object, object]

the function looks like

function search(x, y) {
    if (point.x > x) {
        if (point.y > y) {
            if (nodes[0] == undefined) {
                // do something 1
            else {
                // do something 2
            }
       else {
            if (nodes[1] == undefined) {
                // do something 1
            else {
                // do something 2
            }
      }
  } else {
      if (point.y > y) {
            if (nodes[2] == undefined) {
                // do something 3
            else {
                // do something 4
            }
       else {
            if (nodes[3] == undefined) {
                // do something 5
            else {
                // do something 6
            }
      }
  }
} 

The thing is, every part does something different so I don't think I can compact it that much

also, would it be better to use something like

if (point.x > x && point.y > y && nodes[0] == undefined) { ... }
if (point.x > x && point.y > y && nodes[0] != undefined) { ... }
if (point.x > x && point.y < y && nodes[0] == undefined) { ... }
if (point.x > x && point.y < y && nodes[0] != undefined) { ... }
if (point.x < x && point.y > y && nodes[0] == undefined) { ... }
if (point.x < x && point.y > y && nodes[0] != undefined) { ... }
if (point.x < x && point.y < y && nodes[0] == undefined) { ... }
if (point.x < x && point.y < y && nodes[0] != undefined) { ... }

What would be the best way to write this bit of code?

Thanks

Aucun commentaire:

Enregistrer un commentaire