-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
74 lines (58 loc) · 1.27 KB
/
Copy pathindex.js
File metadata and controls
74 lines (58 loc) · 1.27 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* TODO...
*/
'use strict';
const generator = function* generator(array, comparator) {
const clone = array.slice(0);
for (let i = 0, iLength = clone.length; i < iLength; i++) {
let hasChange = false;
for (let j = 0, jLength = clone.length - 1; j < jLength; j++) {
if (comparator(clone[j], clone[j + 1])) {
const tmp = clone[j];
clone[j] = clone[j + 1];
clone[j + 1] = tmp;
hasChange = true;
}
yield {
array: clone.slice(0),
selected: j + 1
};
}
if (!hasChange) {
break;
}
}
};
const defaultComparator = function defaultComparator(itemA, itemB) {
return itemA > itemB;
};
module.exports = class BubbleSort {
constructor(array, comparator) {
this._array = array;
this._comparator = comparator || defaultComparator;
this._steps = [];
}
compute() {
const genObj = generator(this._array, this._comparator);
this._steps = [...genObj];
}
next() {
if (!this._genObj) {
this._genObj = generator(this._array, this._comparator);
}
return this._genObj.next();
}
getStep(no) {
return this._steps[no];
}
get array() {
return this._array;
}
get result() {
const lastStep = this._steps[this._steps.length - 1];
return lastStep ? lastStep.array : undefined;
}
get steps() {
return this._steps;
}
};