zandaqo / structurae

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

Question about sorted array and push() #33

Closed vanodevium closed 1 year ago

vanodevium commented 1 year ago
class DescSortedArray extends SortedArray {
  static compare(a, b) {
    return b - a
  }
}

const sorted = new DescSortedArray();

sorted.push(3)
sorted.push(1)
sorted.push(5)
sorted.push(4)
sorted.push(2)

console.log(sorted)

Is it normal to see an unsorted array?

DescSortedArray(5) [ 3, 1, 5, 4, 2, unique: false ]

Is there any chance to enable auto sort when I call push() or I have to call sort() after all push() calls?

Thanx!

zandaqo commented 1 year ago

Try this:

class DescSortedArray extends SortedArray {
  static compare(a, b) {
    return b - a > 0 ? 1 : -1;
  }
}

The comparator (SortedArray.compare) return type is -1 | 0 | 1 and returning other values throws it off.

vanodevium commented 1 year ago

@zandaqo Thanks for help! Maybe it would be nice to write this in the readme as a note?