上个行走模拟器完成后,我又构思了下js全排列模拟器代码如下
class List {
constructor(data) {
this.step = 1;
this.status = null;
this.data = data;
this.result = [];
}
run() {
if (this.status !== "over") {
this.nextStep();
return this.run();
} else {
return this.result;
}
}
nextStep() {
if (this.step == 1) {
this.data.forEach((item, index, arr) => {
let leftData = arr.slice(0, index).concat(arr.slice(index + 1));
let data = [item];
this.result.push({ data, leftData });
});
}
if (this.step == this.data.length) {
this.status = "over";
} else {
let temp = [];
this.result.forEach((item) => {
for (let i = 0; i < item.leftData.length; i++) {
temp.push({
data: item.data.concat([item.leftData[i]]),
leftData: item.leftData
.slice(0, i)
.concat(item.leftData.slice(i + 1)),
});
}
});
this.result = temp;
}
this.step += 1;
}
}