zandaqo / structurae

Data structures for high-performance JavaScript applications.
MIT License
694 stars 21 forks source link

Shouldn't SortedArray replace elements upon `push` or `unshift` if unique? #35

Open Swoorup opened 1 year ago

Swoorup commented 1 year ago
interface TimestampedData {
  ts: UTCTimestamp;
}

// @ts-ignore
export class MarketDataArray<T extends TimestampedData> extends SortedArray<T> {
  override unique = true;

  static override compare<T extends TimestampedData>(a: T, b: T): 0 | -1 | 1 {
    if (b.ts == a.ts) return 0;
    else if (b.ts - a.ts > 0) return -1;
    else return 1;
  }
}
const seedData = [{ ts: 0 as UTCTimestamp, value: 1}];
const data = MarketDataArray.from(seedData);
data.push({ ts: 0 as UTCTimestamp, value: 999 }); // value is still 1

If the data is new but is unique by for example timestamp, it appears that there isn't much way around to replacing it using push or unshift?

zandaqo commented 1 year ago

The uniqueness here is judged by the comparator function, if it returns 0 the elements are the same, as it does here:

if (b.ts == a.ts) return 0;

In this case, you can add a second check when timestamps are the same to check the values, something like:

if (b.ts === a.ts) {
  return b.value > a.value ? -1 : 1;
}
Swoorup commented 1 year ago

But that would no longer make it unique and would push duplicates, no?

zandaqo commented 1 year ago

Well, then return 0 from the second check where you consider them to be duplicates.