Skip to content

Commit 7a99930

Browse files
committed
optimize sortableSet to prevent unnecessary sorting
1 parent 1a16a3e commit 7a99930

1 file changed

Lines changed: 30 additions & 1 deletion

File tree

lib/util/SortableSet.js

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,47 @@ module.exports = class SortableSet extends Set {
55
constructor(initialIterable, defaultSort) {
66
super(initialIterable);
77
this._sortFn = defaultSort;
8+
this._lastActiveSortFn = null;
9+
this._isSorted = false;
10+
}
11+
12+
/**
13+
* @param {any} value - value to add to set
14+
* @returns {SortableSet} - returns itself
15+
*/
16+
add(value) {
17+
this._lastActiveSortFn = null;
18+
this._isSorted = false;
19+
super.add(value);
20+
return this;
21+
}
22+
23+
/**
24+
* @returns {void}
25+
*/
26+
clear() {
27+
this._lastActiveSortFn = null;
28+
this._isSorted = false;
29+
super.clear();
830
}
931

1032
/**
1133
* @param {Function} sortFn - function to sort the set
1234
* @returns {void}
1335
*/
1436
sortWith(sortFn) {
37+
if(this._isSorted && sortFn === this._lastActiveSortFn) {
38+
// already sorted - nothing to do
39+
return;
40+
}
41+
1542
const sortedArray = Array.from(this).sort(sortFn);
16-
this.clear();
43+
super.clear();
1744
for(let i = 0; i < sortedArray.length; i += 1) {
1845
this.add(sortedArray[i]);
1946
}
47+
this._lastActiveSortFn = sortFn;
48+
this._isSorted = true;
2049
}
2150

2251
/**

0 commit comments

Comments
 (0)