structurae icon indicating copy to clipboard operation
structurae copied to clipboard

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

Open Swoorup opened this issue 2 years ago • 3 comments

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?

Swoorup avatar May 12 '23 12:05 Swoorup

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;
}

zandaqo avatar May 13 '23 12:05 zandaqo

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

Swoorup avatar May 14 '23 08:05 Swoorup

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

zandaqo avatar May 15 '23 06:05 zandaqo