Sleep Sort

A JavaScript implementation of sleep sort

by Zachary Yaro

HTML

<form id="inputForm">
	<fieldset id="inputFieldset">
		<label for="inputField">Enter a list of comma-separated whole numbers:</label>
		<input type="text" name="input" id="inputField" />
		<button type="submit">Start</button>
	</fieldset>
</form>
<p id="inputDisp"></p>
<p id="outputDisp"></p>

JavaScript

var length, /**        The length of the array being sorted. */
	inputForm, /**     The form wrapping the input field and submit button. */
	inputFieldset, /** The fieldset wrapping the input field and submit button. */
	inputField, /**    The input field itself. */
	inputDisp, /**     The element where the parsed input will be printed. */
	outputDisp; /**    The element where the sorted output will be printed. */

function init() {
	inputForm = document.getElementById('inputForm');
	inputFieldset = document.getElementById('inputFieldset');
	inputField = document.getElementById('inputField');
	inputDisp = document.getElementById('inputDisp');
	outputDisp = document.getElementById('outputDisp');
	
	inputForm.onsubmit = start;
}

/**
 * Parse the input, set up the array, and start the sleep sort.
 * @param {Event} e - The submit event for the input form
 */
function start(e) {
	e.preventDefault();
	
	var inputArr = inputField.value.split(','),
		arr = [];
	
	inputArr.forEach(function (input) {
		// Parse each input and reject any that are not whole numbers.
		input = parseInt(input);
		if (input > 0) {
			arr.push(input);
		}
	});
	
	// Prepare the input and output displays.
	// (If all inputs were invalid, they will just end up blank.)
	inputDisp.innerHTML = arr.join(', ');
	outputDisp.innerHTML = '';
	length = arr.length;
	
	// Only actually run the sort if there were valid inputs.
	if (arr.length > 0) {
		inputFieldset.disabled = true;
		sleepSort(arr);
	}
}

/**
 * Set the sleep sort print timers.
 * @param {Array<Number>} arr - The array of whole numbers to be sorted.
 */
function sleepSort(arr) {
	arr.forEach(function (num) {
		// For each number, N, print it after N ms.
		setTimeout(function () {
			console.log(num);
			printNum(num);
		}, num);
	});
}

/**
 * Print a number to the output field.
 * @param {Number} num - The number to print.
 */
function printNum(num) {
	// If it is not the first number, comma-separate.
	if (outputDisp.innerHTML !== '')...