structurae
structurae copied to clipboard
Shouldn't SortedArray replace elements upon `push` or `unshift` if unique?
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?
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;
}
But that would no longer make it unique and would push duplicates, no?
Well, then return 0 from the second check where you consider them to be duplicates.