A trading dashboard shows a badge next to every closing price: "highest in N days". For each day, N is the span: the number of consecutive days ending on that day, counting the day itself, whose price is less than or equal to that day's price.
Write two things:
priceSpans(prices) takes an array of daily prices and returns a new array of the same length, where position i holds the span of day i.
createSpanTracker() returns an object with a method next(price), which records the next day's price and returns its span. Each tracker keeps its own history.
Rules:
The first day's span is always 1. A day whose previous price is higher also has span 1.
Equal prices count: in [5, 5, 5] the spans are [1, 2, 3].
Prices are finite numbers and may be negative or fractional. If prices is not an array of finite numbers, or next gets something other than a finite number, throw a TypeError.
Do not modify prices.
There can be 200,000 days. Counting backwards day by day is quadratic when prices keep rising; aim for O(n) in total, and O(1) amortised per next call.