-1

timeseries is an array in the following format:

[ {"date": "2012-12-21", "price": 1.234}, ... ]

My code:

function first(timeseries) {
  if (timeseries.length === 0) {
    return undefined;
  }
  var earliestIndex = 0;
  for (var i = 0; i < timeseries.length; i++) {
    if (timeseries[i].date === null) {
      throw new Error("no date");
    } else {
      if(Date.parse(timeseries[i].date) < Date.parse(timeseries[earliestIndex].date)) {
        earliestIndex = i;
      }
    }
  }
  return timeseries[earliestIndex].price;
}

Test result:

testResult

The question did not specify the exact value of date when not provided.

Why is this so? I have already thrown an error.

JrZ
  • 9
  • 2

1 Answers1

1

Couple of suggestions to cover all cases.

  1. Test if timeseries[i].price is null or not before returning.

  2. You may want to try using == instead of === as it will also do the necessary type conversions before check.

Reference: https://stackoverflow.com/a/359509/4874271

Tip: COPY the code and format it here instead of posting photos, would be easier for people to answer. :)

Community
  • 1
  • 1
CodePhobia
  • 1,315
  • 10
  • 19