2017-06-18 08:41:58 +08:00
|
|
|
"use strict";
|
|
|
|
|
|
|
|
module.exports = class SortableSet extends Set {
|
|
|
|
|
|
|
|
constructor(initialIterable, defaultSort) {
|
|
|
|
super(initialIterable);
|
|
|
|
this._sortFn = defaultSort;
|
2017-06-19 20:20:10 +08:00
|
|
|
this._lastActiveSortFn = null;
|
|
|
|
this._isSorted = false;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param {any} value - value to add to set
|
|
|
|
* @returns {SortableSet} - returns itself
|
|
|
|
*/
|
|
|
|
add(value) {
|
|
|
|
this._lastActiveSortFn = null;
|
|
|
|
this._isSorted = false;
|
|
|
|
super.add(value);
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @returns {void}
|
|
|
|
*/
|
|
|
|
clear() {
|
|
|
|
this._lastActiveSortFn = null;
|
|
|
|
this._isSorted = false;
|
|
|
|
super.clear();
|
2017-06-18 08:41:58 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param {Function} sortFn - function to sort the set
|
|
|
|
* @returns {void}
|
|
|
|
*/
|
|
|
|
sortWith(sortFn) {
|
2017-06-19 20:20:10 +08:00
|
|
|
if(this._isSorted && sortFn === this._lastActiveSortFn) {
|
|
|
|
// already sorted - nothing to do
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2017-06-18 08:41:58 +08:00
|
|
|
const sortedArray = Array.from(this).sort(sortFn);
|
2017-06-19 20:20:10 +08:00
|
|
|
super.clear();
|
2017-06-18 08:41:58 +08:00
|
|
|
for(let i = 0; i < sortedArray.length; i += 1) {
|
|
|
|
this.add(sortedArray[i]);
|
|
|
|
}
|
2017-06-19 20:20:10 +08:00
|
|
|
this._lastActiveSortFn = sortFn;
|
|
|
|
this._isSorted = true;
|
2017-06-18 08:41:58 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @returns {void}
|
|
|
|
*/
|
|
|
|
sort() {
|
|
|
|
this.sortWith(this._sortFn);
|
|
|
|
}
|
|
|
|
};
|