tidepool-org/tideline — pull request #13 by nicolashery (2014-02-19 11:12:05+00:00)
Title: Avoid error on smaller basal datasets

@jebeck We spoke of a small issue I had when trying to work off of a subset of `example/device-data.json`. What follows is not really a solution, but rather a fix that avoids the error and makes the basal plot possible on a smaller dataset.

Since I'm not very familiar with the code, you might understand better where the error came from and come up with something more elegant. If so, feel free to make your own change and close this.

## How to reproduce the error

Off of `master`, you can do the following. I'm going to work with the JSON tool `jq` (http://stedolan.github.io/jq/) to build data sets (install with `brew install jq`).

```bash
$ mkdir -p tmp
$ cp example/device-data.json tmp/device-data.json
$ cat tmp/device-data.json | jq '"2014-03-05" as $d | ([.[] | select(.deviceTime >= $d or .utcTime >= $d or .start >= $d)])' > tmp/device-data-100basals.json
$ cat tmp/device-data.json | jq '"2014-03-10" as $d | ([.[] | select(.deviceTime >= $d or .utcTime >= $d or .start >= $d)])' > tmp/device-data-58basals.json

# Now you can switch between datasets with
$ cp tmp/device-data-100basals.json example/device-data.json
$ cp tmp/device-data-58basals.json example/device-data.json
```

Using the above, you'll notice that the `device-data-100basals.json` works, but the `device-data-58basals.json` produces an error.

## How to avoid the error

I happens in the last `if` block of the snippet:

```javascript
function basal(selection) {
selection.each(function(currentData) {
// to prevent blank rectangle at beginning of domain
var index = opts.data.indexOf(currentData[0]);
// when near left edge currentData[0] will have index 0, so we don't want to decrement it
if (index !== 0) {
index--;
}
while ((index >= 0) && (opts.data[index].vizType !== 'actual')) {
index--;
}
// when index === 0 might catch a non-basal
if (opts.data[index].type === 'basal-rate-segment') {
currentData.unshift(opts.data[index]);
}
```

If you add a `console.log(currentData)` at the beginning of the `selection.each` callback, you'll notice that for the smaller dataset it starts off as an empty array `[]`, and then has some data. This isn't the case for bigger datasets. I'm not sure why, but I decided to put in a check at the beginning and skip over those empty `currentData` arrays.

Let me know what you think :)