-2

this.startOffset and this.endOffset in the following code are values I'm using to select individual characters within nodes:

this.startOffset = this.node.length - 1 ||
  this.node.firstChild.length - 1 ||
  this.node.childNodes.item(0).length - 1 ||
  this.node.childNodes.item(0).firstChild.length - 1

this.endOffset = this.node.length ||
  this.node.firstChild.length ||
  this.node.childNodes.item(0).firstChild.length

I'm using -1 in this.startOffset because that's the value at the beginning of a character. (e.g. 0,1 will select the first character in the node.)

However, because this.node.childNodes.item(0).length - 1 will become 0 in the first character, it will return false instead of 0 and the code will reach this.node.childNodes.item(0).firstChild.length - 1, causing an error.

How can I make it so that 0 doesn't return false, and instead sets this.startOffset to 0?

alexchenco
  • 53,565
  • 76
  • 241
  • 413
  • will it not be cleaner to just remove `-1` from the condition? – gurvinder372 May 02 '16 at 10:25
  • 2
    this http://stackoverflow.com/questions/523643/difference-between-and-in-javascript should help – Keyur Sakaria May 02 '16 at 10:26
  • @gurvinder372 You mean to place it somewhere else? – alexchenco May 02 '16 at 10:26
  • I mean using `children` instead of `childNodes` since `children` doesn't return text nodes. – gurvinder372 May 02 '16 at 10:28
  • 1
    Downvoting because the code is overly complex and if it was properly structured the question wouldn't be necessary in the first place. – Bartek Banachewicz May 02 '16 at 10:28
  • 1
    *"How can I make it so that 0 doesn't return false, and instead sets this.startOffset to 0?"* The code presented in your first code block will only set `startOffset` to a number, not `false`, provided those `length` properties are all numbers. It will be the first of those numbers that isn't `0`, or `0` if they all are. – T.J. Crowder May 02 '16 at 10:31
  • I don't get why are you using boolean conditions to set an integer value, but you could simply add a `(condition) ? 1 : 0` at the end, or use `+(condition)`, or `(condition) | 0` – Jcl May 02 '16 at 10:31

2 Answers2

1

If text node is a concern then, try using children instead

this.startOffset = this.children.length ||
  this.children.item(0).children.length;

This will skip text nodes and return boolean based on whether or not child-node and its child-nodes are present.

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
1

You could use ternary operator to return whatever you want as a value

this.startOffset = (condition) ? 1 : 0;
koninos
  • 4,969
  • 5
  • 28
  • 47