Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Swoorup opened this issue May 12, 2023 · 3 comments
Open

Comments

@Swoorup
Copy link
Contributor

Swoorup commented May 12, 2023

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
Copy link
Owner

zandaqo commented May 13, 2023

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
Copy link
Contributor Author

Swoorup commented May 14, 2023

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

@zandaqo
Copy link
Owner

zandaqo commented May 15, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants