JSFiddle - React, Tailwind, and code Playground
JavaScript
// -----------------------------------------
// Test input, common series of commands
// -----------------------------------------
var testCommands = ["a", 1.1, 2.2, "b", 0.0, 0.0, "c", 1.0, 2.0, 3.0, 4.0, 'z'];
while (testCommands.length < 10000)
testCommands = testCommands.concat(testCommands);
// -----------------------------------------
// Test runner, fresh data and timed run
// -----------------------------------------
function testFunc(str, func) {
var commands = testCommands.slice(0);
var start = new Date;
var result = func(commands);
var end = new Date;
console.log(str, result, (end - start) + "ms")
var p = document.body.appendChild(document.createElement("p"));
p.textContent = str + " Output (" + result + ") Time (" + (end-start) + "ms)";
}
// --------------------------------
// Continually slicing an array
// --------------------------------
function arrayManipulation(commands) {
var total = 0;
function something(arr) { total += arr.length; }
function consume(commands, length) {
something(commands.slice(1, length + 1));
return commands.slice(length + 1);
}
while (commands.length) {
switch (commands[0]) {
case 'a':
commands = consume(commands, 2);
break;
case 'b':
commands = consume(commands, 2);
break;
case 'c':
commands = consume(commands, 4);
break;
default:
commands = consume(commands, 1);
break;
}
}
return total;
}
// -------------------------------------------
// Walking over an array, no modifications
// -------------------------------------------
function arrayWalking(commands) {
var total = 0;
function something(arr) { total += arr.length; }
var index = 0;
function consume(commands, length) {
something(commands.slice(index + 1,...