Javascript Console Test

Run javascript code and display the output

by Robert Dodd

HTML

<script src="//code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="//stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- 
  Bootstrap docs: https://getbootstrap.com/docs
-->

<div class="container">
  <h1>Test</h1>
  <pre id="pre" class="form-control"></pre>
</div>

CSS

.row {
  background: #f8f9fa;
  margin-top: 20px;
}

.col {
  border: solid 1px #6c757d;
  padding: 10px;
}

JavaScript

/**
 * Logger for sending output to the page.
 */
function Logger(elId) {
	var self = this;

  this.element = document.getElementById(elId);
  this.output = null;

	/**
   * Log output and display it on the page.
   */
	this.log = function(data) {
  	
    // Add a new line if output isn't empty
    if (this.output) {
    	this.output += '\n';
    } else {
    	this.output = '';
    }
    
    // Append new data to output
    this.output += data.toString();
    this.element.innerHTML = this.output;
  }

	/**
   * Log item as a json string.
   */
	this.logJson = function(data) {
  	var jsonString = JSON.stringify(data, null, 2);
		this.log(jsonString);
  }
}

// Create a logger which logs to the `pre` element.
var logger = new Logger('pre');

// Unordered list
var items = [
	{id: 1},
	{id: 2},
	{id: 3}
];
 
// The desired order (with one missing to test it get's palced at the end)
var order = [4, 2, 1];

/**
 * Sort a list according to a list of keys.
 */
function sortByList(unorderedList, orderList, keyFunc) {

  /**
   * Compares two blocks for soring based on their position in
   * the `self.blockOrder` list.
   */
  function compare(a, b) {
  	var aId = keyFunc(a);
  	var bId = keyFunc(b);
    var aIndex = orderList.indexOf(aId);
    var bIndex = orderList.indexOf(bId);
    if (aIndex == -1) { aIndex = orderList.length; }
    if (bIndex == -1) { bIndex = orderList.length; }
    return aIndex - bIndex;
  }

  unorderedList.sort(compare);
}

var keyFunc = function(item) {
	return item.id;
}

// Log output
sortByList(items, order, keyFunc);
logger.logJson(items);

// Log output
order = [];
sortByList(items, order, keyFunc);
logger.logJson(items);

// Log output
items = [];
sortByList(items, order, keyFunc);
logger.logJson(items);





/**
 * This is just here to add padding at the bottom of the file.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 */