You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

106 lines
2.7 KiB

/**
*
*/
function Visualizer(parent) {
this.parent = parent;
this.sorter = null;
this.paused = true;
var sorterSidebarContainer = document.createElement('div');
sorterSidebarContainer.className = 'sorter-sidebar';
parent.appendChild(sorterSidebarContainer);
var properties = this.initProperties();
parent.appendChild(properties);
var controls = this.initControls();
parent.querySelector('.sorter-sidebar').appendChild(controls);
var messages = this.initMessages();
parent.querySelector('.sorter-sidebar').appendChild(messages);
var range = this.initRange();
parent.querySelector('.sorter-sidebar').appendChild(range);
switch(parent.attributes['data-algorithm'].value) {
case 'quick':
this.sorter = new QuickSort();
break;
case 'merge':
this.sorter = new MergeSort();
break;
case 'selection':
this.sorter = new SelectionSort();
break;
case 'bubble':
this.sorter = new BubbleSort();
break;
case 'insertion':
this.sorter = new InsertionSort();
break;
case 'shell':
this.sorter = new ShellSort();
break;
case 'radix':
this.sorter = new RadixSort();
break;
default:
throw new Error('Unrecognized sort type.');
}
this.initItems(10);
};
// Public static properties (mutable)
Visualizer.spacerW = 5;
Visualizer.itemW = 14;
Visualizer.itemH = 50;
Visualizer.itemY = 20;
/**
*
*/
Visualizer.calculateX = function(index) {
return Visualizer.spacerW + index * (Visualizer.itemW + Visualizer.spacerW)
};
/**
* Instructions contain a string with the name of a function in this object which is called to perform an action.
*/
Visualizer.prototype.followInstruction = function() {
if (this.instructionIndex >= this.sorter.instructions.length) {
return;
}
var instruction = this.sorter.instructions[this.instructionIndex];
var operation = this[instruction[0]];
var delay = instruction[1];
console.log(instruction);
// NOTE interesting (anti?)pattern here.
// NOTE use of call() vs apply() (apply only delivered first array item as string)
if (typeof operation === 'function') {
operation.call(this, instruction);
if (delay === 0) {
this.instructionIndex++;
this.followInstruction();
}
else if (this.paused === false) {
this.instructionIndex++;
setTimeout(this.followInstruction.bind(this), delay);
}
}
else {
console.error(i);
throw new Error('Unidentified instruction.');
}
};