This repository has been archived on 2022-08-19. You can view files and clone it, but cannot push or open issues or pull requests.
hydrogen-web/src/observable/list/SortedArray.js

61 lines
1.6 KiB
JavaScript
Raw Normal View History

2019-05-20 00:19:46 +05:30
import BaseObservableList from "./BaseObservableList.js";
import sortedIndex from "../../utils/sortedIndex.js";
2019-05-20 00:19:46 +05:30
export default class SortedArray extends BaseObservableList {
constructor(comparator) {
super();
this._comparator = comparator;
this._items = [];
}
setManyUnsorted(items) {
this.setManySorted(items);
}
setManySorted(items) {
// TODO: we can make this way faster by only looking up the first and last key,
// and merging whatever is inbetween with items
// if items is not sorted, 💩🌀 will follow!
// should we check?
// Also, once bulk events are supported in collections,
// we can do a bulk add event here probably if there are no updates
// BAD CODE!
for(let item of items) {
this.set(item);
}
2019-05-20 00:19:46 +05:30
}
set(item, updateParams = null) {
2019-05-20 00:19:46 +05:30
const idx = sortedIndex(this._items, item, this._comparator);
if (idx >= this._items.length || this._comparator(this._items[idx], item) !== 0) {
2019-05-20 00:19:46 +05:30
this._items.splice(idx, 0, item);
this.emitAdd(idx, item)
2019-05-20 00:19:46 +05:30
} else {
this._items[idx] = item;
this.emitUpdate(idx, item, updateParams);
2019-05-20 00:19:46 +05:30
}
}
2019-07-27 01:33:57 +05:30
get(idx) {
return this._items[idx];
}
remove(idx) {
const item = this._items[idx];
this._items.splice(idx, 1);
this.emitRemove(idx, item);
}
2019-05-20 00:19:46 +05:30
get array() {
return this._items;
}
get length() {
return this._items.length;
}
[Symbol.iterator]() {
return this._items.values();
}
}