JSFiddle - React, Tailwind, and code Playground
by dashk
HTML
<div id="result">
</div>
JavaScript
/**
* Given an input (which may include multiple lines), reverse the order of each "word"
* within the same line, and ignore any empty lines in the output
*
* @param {String} line Input
* @return {String} Output as a string
**/
function codeEvalExecute(line)
{
// Make sure input has something before processing
if (!line || line.length == 0) {
return "";
}
// Split line up by new lines
var lines = line.split("\n");
var output = [];
// Loop through each line
for (var i = 0; i < lines.length; ++i) {
// Check if line's empty
if (!lines[i] || lines[i].length == 0) {
// Ignore line if it is
continue;
}
// Tokenize the line
var currentLine = lines[i].split(" ");
var currentLineOutput = [];
// Loop from the end of the array back to the front (Not the most elegant solution. Whoops!)
for (var j = currentLine.length; j >= 0; --j) {
// Add current word to output
currentLineOutput.push(currentLine[j]);
}
// Add the line back together
output.push(currentLineOutput.join(" "));
}
// Join all output back together with a new line character
return output.join("\n");
}
var result = codeEvalExecute("");
document.getElementById("result").innerHTML = result.replace(new RegExp(/\n/ig), "1");