/** * */ function Visualizer(parent) { this.actions = []; 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(this); break; case 'merge': this.sorter = new MergeSort(this); break; case 'selection': this.sorter = new SelectionSort(this); break; case 'bubble': this.sorter = new BubbleSort(this); break; case 'insertion': this.sorter = new InsertionSort(this); break; case 'shell': this.sorter = new ShellSort(this); break; case 'radix': this.sorter = new RadixSort(this); break; default: throw new Error('Unrecognized sort type.'); } this.initItems(10); }; // Static properties (mutable) Visualizer.spacerW = 5; Visualizer.itemW = 14; Visualizer.itemH = 50; Visualizer.padding = 10; /** * Static. */ Visualizer.calculateX = function(index) { return Visualizer.spacerW + index * (Visualizer.itemW + Visualizer.spacerW) }; /** * */ Visualizer.prototype.instruct = function() { this.actions.push(arguments); return this; }; /** * Instructions contain a string with the name of a function in this object which is called to perform an action. */ Visualizer.prototype.go = function() { if (this.actionIndex >= this.actions.length) { return; } var obj = this.actions[this.actionIndex]; var instruction = new Array(); for (var key in obj) { if (obj[key].hasOwnProperty) { instruction.push(obj[key]); } } var delay = instruction[1]; var args = instruction.slice(1); // TODO add tabs for best/worst cases // TODO add links to stats // TODO fix init slider // TODO heap sort // TODO extra memory // TODO width and height updates // 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); instruction[0].apply(this, args); if (delay === 0) { this.actionIndex++; this.go(); } else if (this.paused === false) { this.actionIndex++; setTimeout(this.go.bind(this), delay); } }; /** * */ Visualizer.prototype.reset = function() { this.actionIndex = 0; this.message(0, 1, ''); this.message(0, 2, ''); this.message(0, 3, ''); this.message(0, 4, ''); this.message(0, 5, ''); this.unhighlight(); this.unfade(); this.groups .transition().duration(100) .attr('transform', function doTransform(d, i) { d.index = i; return `translate(${Visualizer.calculateX(i)}, ${Visualizer.itemY})`; }); };