forked from webpack/webpack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortableSet.js
More file actions
57 lines (50 loc) · 1.05 KB
/
SortableSet.js
File metadata and controls
57 lines (50 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
"use strict";
module.exports = class SortableSet extends Set {
constructor(initialIterable, defaultSort) {
super(initialIterable);
this._sortFn = defaultSort;
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();
}
/**
* @param {Function} sortFn - function to sort the set
* @returns {void}
*/
sortWith(sortFn) {
if(this._isSorted && sortFn === this._lastActiveSortFn) {
// already sorted - nothing to do
return;
}
const sortedArray = Array.from(this).sort(sortFn);
super.clear();
for(let i = 0; i < sortedArray.length; i += 1) {
this.add(sortedArray[i]);
}
this._lastActiveSortFn = sortFn;
this._isSorted = true;
}
/**
* @returns {void}
*/
sort() {
this.sortWith(this._sortFn);
}
};