Coding Challenge
Simple coding challenge for applicants.
by klenwell
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div id="challenge">
<h3>Coding Challenge</h3>
<p>Fork this fiddle and implement the following user story:</p>
<blockquote>
As a user, when I click the Sort Now! button, I want the numbers in
the input field sorted in ascending order and output in an ordered list.
</blockquote>
<div id="instructions">
<h4>Tips</h4>
<ul>
<li>Do not edit this fiddle. Use the fork button above.</li>
<li>Sort the comma-separated values in input field.</li>
<li>Output values in ordered list below.</li>
<li>For extra credit, color negative values <span class="red">red</span>.</li>
<li>Feel free to use the browser console. Don't be afraid to ask for help, either.</li>
</ul>
</div>
<div id="input">
<h4>Inputs</h4>
<form class="form-inline">
<div class="form-group">
<label for="exampleInputName2">Name</label>
<input type="text"
class="form-control"
id="numbers"
value="-2, 39, 0, 66, 14, -11, 98, 7, 44, -50"
disabled>
</div>
<button id="sorter" type="submit" class="btn btn-primary">Sort Now!</button>
</form>
</div>
<hr/>
<div id="output">
<h4>Sorted List</h4>
<ol></ol>
</div>
</div>
CSS
div#challenge {
padding: 8px;
}
.red {
color: red;
}
JavaScript
function sortNumberList(numberList) {
// TODO: numberList will be an array of integers. Sort in ascending order
// and return as an array.
var sortedList = [];
return sortedList;
}
$('button#sorter').on('click', sortInputAndOutput);
function sortInputAndOutput() {
var numberList = $('div#input input').val().split(',');
var sortedNumbers = sortNumberList(numberList);
outputNumbersToOrderedList(sortedNumbers);
return false; // Do not submit. JSFiddle will give us an error.
}
function outputNumbersToOrderedList(orderedList) {
// orderedList will be a pre-sorted array of integers. Appends numbers as list
// elements in the output div.
var $ol = $('div#output ol');
$.each(orderedList, function(_, number) {
// TODO: Make negative values red.
var $li = $('<li />').text(number);
$ol.append($li);
});
}
function sortIntegers(a, b) {
// Source: http://stackoverflow.com/a/1063027/1093087
// Usage: myArray.sort(sortIntegers);
return parseInt(a) - parseInt(b);
}