FizzBizz 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>FizzBizz Coding Challenge</h3>
  <p>Fork this fiddle and implement the following user story:</p>
  <blockquote>
    As a user, when I click the Fizz Now! button, I want numbers logged according to the requirements below.
  </blockquote>
  
  <div id="instructions">
    <h4>Requirements</h4>
    <ul>
      <li>Do not edit this fiddle. Use the fork button above.</li>
      <li>Update the fizzBizz function below to do the following:</li>
        <ul>
          <li>If <tt>number</tt> is divisible by 3, return 'fizz'.</li>
          <li>If <tt>number</tt> is divisible by 5, return 'bizz'.</li>
          <li>If <tt>number</tt> is divisible by 3 and 5, return 'fizzbizz'.</li>
          <li>Otherwise, return 'not'.</li>
        </ul>
      <li>Feel free to use the browser console. Don't be afraid to ask for help, either.</li>
    </ul>
  </div>
  
  <div id="input">
    <form class="form-inline">
      <button id="main" type="submit" class="btn btn-primary">Fizz Now!</button>
    </form>
  </div>
  
  <hr/>

  <div id="output">
    <h4>FizzBizz Log</h4>
    <table class="table">
      <thead>
        <tr>
          <th>Date Stamp</th>
          <th>Number</th>
          <th>Result</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>
  </div>
</div>

CSS

div#challenge {
  padding: 8px;
}

.red {
  color: red;
}

JavaScript

function fizzBizz(number) {
	// TODO: number is an integer. Return 'fizz', 'bizz', 'fizzbizz', or 'not'
  // according to rules above.
  var result = null;
  
  return result;
}

$('button#main').on('click', main);

function main() {
  var maxCycles = 10;
  var cycles = 0;
  
  var interval = setInterval(function() {
    cycles += 1;
    var number = randomNumberBetween(0, 100);
    var result = fizzBizz(number);
    logResult(number, result);  
    
    if ( cycles >= maxCycles ) {
      logResult('Stop.');
      clearInterval(interval);
    }
  }, 500);
  
  return false;	// Do not submit. JSFiddle will give us an error.
}

function randomNumberBetween(min, max) {
  // http://stackoverflow.com/a/1527820/1093087
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function logResult(number, result) {
  var timestamp = new Date().getTime();
  
  var $tbody = $('div#output table tbody');
  var $tr = $('<tr />');
  var $td1 = $('<td />').text(timestamp);
  var $td2 = $('<td />').text(number);
  var $td3 = $('<td />').text(result);
  
  $tr.append($td1);
  $tr.append($td2);
  $tr.append($td3);
  $tbody.append($tr);
}