пятница, 19 февраля 2016 г.

JavaScript console code executor (evaluator)

<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Console</title>
</head>
<body>

<div id="output" style="overflow: auto; width: 500px; height: 300px; border: 2px solid black;"></div>
<textarea id="input" style="width: 500px; height: 200px; border: 2px solid black;"></textarea>
<br />
<input id="run" type="button" value="Run" />

<script>

function Evaluator () {
    this.environment = {};
    this.console = {
        log: function (message) {console.log('>>> ' + message);}
    };
}

Evaluator.prototype.evaluate = function (codeString) {
    try {
        codeString = rewriteDeclarations(codeString);
        var __environment__ = this.environment
            , console = this.console; // Temporarily shadow the global console for eval()
        with (__environment__) {
            return JSON.stringify(eval(codeString));
        }
    } catch (error) {
        return error.toString();
    }
}

function rewriteDeclarations (codeString) {
    codeString = "\n" + codeString; // Prefix a newline so that search and replace is simpler
    codeString = codeString.replace(/\nvar\s+(\w+)\s*=/g, '\n__environment__.$1 =');
    codeString = codeString.replace(/\nfunction\s+(\w+)/g, '\n__environment__.$1 = function');
    return codeString.slice(1); // Remove prefixed newline
}

var output = document.getElementById('output')
    , input = document.getElementById('input')
    , run = document.getElementById('run')
    , e = new Evaluator();

run.onclick = function () {
    var code = input.value
        , result = document.createElement('p');
    result.innerHTML = e.evaluate(code);
    output.appendChild(result);
};

</script>
</body>
</html>

Комментариев нет:

Отправить комментарий