Skip to main content
replaced http://codegolf.stackexchange.com/ with https://codegolf.stackexchange.com/
Source Link

Has support for some parts of display, forvalues, list, generate, and set obs. In addition, it has some supports for macro (STATA's variables) creation and use. It supports enough operations for some of the simpler answers that have been posted on this site, such as http://codegolf.stackexchange.com/questions/40376/evolution-of-hello-world/40406?s=4|0.2560#40406https://codegolf.stackexchange.com/questions/40376/evolution-of-hello-world/40406?s=4|0.2560#40406, http://codegolf.stackexchange.com/questions/44949/generate-the-st%c3%b6hr-sequence/44999?s=2|0.5123#44999https://codegolf.stackexchange.com/questions/44949/generate-the-st%c3%b6hr-sequence/44999?s=2|0.5123#44999, http://codegolf.stackexchange.com/questions/35862/make-me-an-alphabet-tree/35869?s=5|0.2288#35869https://codegolf.stackexchange.com/questions/35862/make-me-an-alphabet-tree/35869?s=5|0.2288#35869 (replace single quotes with double quotes and make it 3 lines instead of 1). This is a work in progress, and I hope to continue it soon, but I figured I would at least put something here for now.

Has support for some parts of display, forvalues, list, generate, and set obs. In addition, it has some supports for macro (STATA's variables) creation and use. It supports enough operations for some of the simpler answers that have been posted on this site, such as http://codegolf.stackexchange.com/questions/40376/evolution-of-hello-world/40406?s=4|0.2560#40406, http://codegolf.stackexchange.com/questions/44949/generate-the-st%c3%b6hr-sequence/44999?s=2|0.5123#44999, http://codegolf.stackexchange.com/questions/35862/make-me-an-alphabet-tree/35869?s=5|0.2288#35869 (replace single quotes with double quotes and make it 3 lines instead of 1). This is a work in progress, and I hope to continue it soon, but I figured I would at least put something here for now.

Has support for some parts of display, forvalues, list, generate, and set obs. In addition, it has some supports for macro (STATA's variables) creation and use. It supports enough operations for some of the simpler answers that have been posted on this site, such as https://codegolf.stackexchange.com/questions/40376/evolution-of-hello-world/40406?s=4|0.2560#40406, https://codegolf.stackexchange.com/questions/44949/generate-the-st%c3%b6hr-sequence/44999?s=2|0.5123#44999, https://codegolf.stackexchange.com/questions/35862/make-me-an-alphabet-tree/35869?s=5|0.2288#35869 (replace single quotes with double quotes and make it 3 lines instead of 1). This is a work in progress, and I hope to continue it soon, but I figured I would at least put something here for now.

Added replace command
Source Link
bmarks
  • 2.1k
  • 11
  • 13

Edit: added replace and checks for generate.

<html>
<body>
Input
<textarea id="input"></textarea>
<br/>
Code
<textarea id="code"></textarea>
<br/>
<button>Run</button>
<br/>Output:
<textarea id="output"></textarea>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">

$(function(){
    _N=0
    dataset=[];
    locals=[];
    globals=[];
    $output=$('#output');
    $input=$('#input');
    inputs=[];
    commands=[];
    comTable = [];
    comTable['di'] = 'display';
    comTable['dis'] = 'display';
    comTable['disp'] = 'display';
    comTable['displ'] = 'display';
    comTable['displa'] = 'display';
    comTable['display'] = 'display';
    comTable['loc'] = 'local';
    comTable['loca'] = 'local';
    comTable['local'] = 'local';
    comTable['gl'] = 'global';
    comTable['glo'] = 'global';
    comTable['glob'] = 'global';
    comTable['globa'] = 'global';
    comTable['global'] = 'global';
    comTable['set']='set';
    comTable['g'] = 'generate';
    comTable['ge'] = 'generate';
    comTable['gen'] = 'generate';
    comTable['gene'] = 'generate';
    comTable['gener'] = 'generate';
    comTable['genera'] = 'generate';
    comTable['generat'] = 'generate';
    comTable['generate'] = 'generate';
    comTable['replace'] = 'replace';
    comTable['l']='list';
    comTable['li']='list';
    comTable['lis']='list';
    comTable['list']='list';
    comTable['forv']='forvalues';
    comTable['forva']='forvalues';
    comTable['forval']='forvalues';
    comTable['forvalu']='forvalues';
    comTable['forvalue']='forvalues';
    comTable['forvalues']='forvalues';
    comTable['}']='No Operation';
    opTable=[];
    opTable['display']=[];
    opTable['display']['_r']='_request';
    opTable['display']['_re']='_request';
    opTable['display']['_req']='_request';
    opTable['display']['_requ']='_request';
    opTable['display']['_reque']='_request';
    opTable['display']['_reques']='_request';
    opTable['display']['_request']='_request';
    opTable['set']=[];
    opTable['set']['ob']='obs';
    opTable['set']['obs']='obs';
});
$('button').click(function () {
    _N=0
    dataset=[];
    inputNum=0;
    inputs=$input.val().split('\n');
    $output.val('');
    locals=[];
    globals=[];
    var code = $('#code').val();
    commands = code.split('\n');
    var tokens = [];
    commands.forEach(function (entry) {
        tokens.push(entry.match(/(?:[^\s"]+|"[^"]*")+/g) );
    });
    var error = '';
    var nextIndex=0;
    $.each(tokens,function (index,entry) {
        if(nextIndex!==index){
            return true;
        }
        var tok = entry[0];
        entry[0] = comTable[tok];
        if (entry[0] === undefined) {
            error = tok + ' is not a recognized command';
            outputError(error);
            return false;
        }
        nextIndex+=execute(entry,index);
        if(!nextIndex){
            return false;
        }
    });
});

function execute(command,ind){
    switch(command[0]){
        case 'display':
            return executeDisplay(command);
        case 'local':
            return executeLocal(command);
        case 'global':
            return executeGlobal(command);
        case 'set':
            return executeSet(command);
        case 'generate':
            return executeGenerate(command);
        case 'replace':
            return executeReplace(command);
        case 'list':
            return executeList(command);
        case 'forvalues':
            return executeForvalues(command,ind);
    }
}

function executeForvalues(command,ind){
    var re=/(\w+)=(.+)\((.+)\)(.+){/;
    var arr=re.exec(command[1]);
    if(arr==null){
        outputError('invalid format to command forvalues: '+command[1]);
        return false;
    }
    var locName=evaluate(arr[1],0);
    var i=Number(evaluate(arr[2],0));
    var increment=Number(evaluate(arr[3],0));
    var maximum=evaluate(arr[4],0);
    console.log(locName+' '+i+' '+increment+' '+maximum);
    maximum=Number(maximum);
    var curInd=ind+1;
    for(;i<=maximum;i+=increment){
        locals[locName]=i;
        globals['_'+locName]=i;
        for(curInd=ind+1;commands[curInd]!=='}';curInd++){
            var entry=commands[curInd].match(/(?:[^\s"]+|"[^"]*")+/g);
            var tok = entry[0];
            entry[0] = comTable[tok];
            if (entry[0] === undefined) {
                error = tok + ' is not a recognized command';
                outputError(error);
                return false;
            }
            console.log(entry);
            if(!execute(entry)){
                return false;
            }
            console.log($output.val());
        }
    }
    return curInd-ind;
}

function executeList(command){
    var out='\t'+Object.keys(dataset).join('\t')+'\n';
    for(var i=0;i<_N;i++){
        out+=(i+1)+'\t';
        Object.keys(dataset).forEach(function(element){
            out+=dataset[element][i]+'\t';out+=dataset[element][i]===undefined?'.':dataset[element][i]+'\t';
        })
        out+='\n';
    }
    $output.val(function(i,val){
        return val+out;
    });
    return 1;
}

function executeGenerate(command){
    var parts=command[1].split('=');
    if(dataset[parts[0]]){
        outputError('variable '+parts[0]+' already exists.');
        return false;
    }
    dataset[parts[0]]=[];
    for(var i=0;i<_N;i++){
        dataset[parts[0]][i]=evaluateVariables(parts[1],i);
    }
    return 1;
}

function executeReplace(command){
    var parts=command[1].split('=');
    if(!dataset[parts[0]]){
        outputError('variable '+parts[0]+' does not exist.');
        return false;
    }
    for(var i=0;i<_N;i++){
        dataset[parts[0]][i]=evaluateVariables(parts[1],i);
    }
    return 1;
}

function evaluateVariables(str,i){
    return eval(str.replace('_n',i+1));
}

function executeSet(command){
    if(opTable['set'][command[1]]=='obs'){
        _N=parseInt(command[2],10);
        return 1;
    }
    outputError('invalid option for command set: '+command[1]);
    return false;
}

function executeLocal(command){
    var parts=command[1].split('=');
    var name,value;
    if(parts.length==1){
        var re0=/^\+\+(\w+)$/;
        var re1=/^--(\w+)$/;
        var re2=/^(\w+)\+\+$/;
        var re3=/^(\w+)--$/;
        var arr=re0.exec(parts[0])||re1.exec(parts[0])||re2.exec(parts[0])||re3.exec(parts[0]);
        if(arr!=null){
            name=arr[1];
            if(parts[0].indexOf('-')>-1){
                value=globals[name]-1;
            }
            else{
                value=globals[name]+1;
            }
        }
        else{
            parts[1]=command[2];
        }
    }
    if(!value){
        value=evaluate(parts[1],0);
    }
    if(typeof value==='undefined'){
        return false;
    }
    if(!name){
        name=evaluate(parts[0]);
    }
    locals[name]=value;
    globals['_'+name]=value;
    return 1;
}

function executeGlobal(command){
    var parts=command[1].split('=');
    var name,value;
    if(parts.length==1){
        var re0=/^\+\+(\w+)$/;
        var re1=/^--(\w+)$/;
        var re2=/^(\w+)\+\+$/;
        var re3=/^(\w+)--$/;
        var arr=re0.exec(parts[0])||re1.exec(parts[0])||re2.exec(parts[0])||re3.exec(parts[0]);
        if(arr!=null){
            name=arr[1];
            if(parts[0].indexOf('-')>-1){
                value=globals[name]-1;
            }
            else{
                value=Number(globals[name])+1;
            }
        }
        else{
            parts[1]=command[2];
        }
    }
    if(!value){
        value=evaluate(parts[1],0);
    }
    if(typeof value==='undefined'){
        return false;
    }
    if(!name){
        name=evaluate(parts[0]);
    }
    if(name.charAt(0)=='_'){
        locals[name.substring(1)]=value;
    }
    globals[name]=value;
    return 1;
}

function executeDisplay(command){
    for(var i=1;i<command.length;i++){
        var comVal=command[i];
        $output.val(function(ind,val){
            var re=/^(\w+)/;
            var arr=re.exec(command[i]);
            if(arr!==null&&opTable['display'][arr[0]]=='_request'){
                re=/^\w+\((\w+)\)/;
                arr=re.exec(command[i]);
                var input=getInput();
                globals[arr[1]]=input;
                if(arr[1].charAt(0)=='_'){
                    locals[arr[1].substring(1)]=input;
                }
                return val;
            }
            return val+evaluate(command[i],0)+'\n';
        });
    }
    return 1;
}

function getInput(){
    var x=inputs[inputNum];
    inputNum++;
    return x;
}

function evaluate(str,captured){
    str=String(str);
    var index=str.indexOf('"');
    if(index==-1){
        return evaluate2(str);
    }
    var secondIndex=str.indexOf('"',index+1);
    while(secondIndex>0&&str.charAt(secondIndex-1)=='\\'){
        secondIndex=str.indexOf('"',secondIndex+1);
    }
    if(secondIndex<0){
        if(!captured){
            var error ='unmatched quotes';
            outputError(error);
            return undefined;
        }
        return '';
    }
    return (index>0?evaluate2(str.substring(0,index)):'')+evaluate2(str.substring(index,secondIndex+1))+(secondIndex<str.length-1?evaluate(str.substring(secondIndex)):'');
}

function evaluate2(str){
    var index=str.indexOf('`');
    if(index==-1){
        return evaluate3(str);
    }
    var secondIndex=str.indexOf('\'',index+1);
    while(secondIndex>0&&str.charAt(secondIndex-1)=='\\'){
        secondIndex=str.indexOf('\'',secondIndex+1);
    }
    if(secondIndex<0){
        return evaluate3(str);
    }
    var value=locals[str.substring(index+1,secondIndex)];
    if(typeof value==='undefined'){
        value='';
    }
    return evaluate((index>0?str.substring(0,index):'')+value+(secondIndex<str.length-1?str.substring(secondIndex+1):''));
}

function evaluate3(str){
    var re=/\$(\w+)/;
    var arr=re.exec(str);
    if(arr!==null){
        var index=arr.index;
        var length=arr[0].length;
        var value=globals[arr[1]];
        str=str.substring(0,index)+value+str.substring(index+length);
        return evaluate(str);
    }
    try {
        var value=eval(str.replace('_N',_N));
        return value;
    }catch(err){
        console.log(str);
        return str;
    }
}

function evaluate4(str){
    try {
        var value=eval(str);
        return value;
    }catch(err){
        console.log(str);
        return undefined;
    }
}

function outputError(error) {
    $output.val(function(ind,val){
        return val+error+'\n';
    });
}
</script>
</body>
</html>
<html>
<body>
Input
<textarea id="input"></textarea>
<br/>
Code
<textarea id="code"></textarea>
<br/>
<button>Run</button>
<br/>Output:
<textarea id="output"></textarea>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">

$(function(){
    _N=0
    dataset=[];
    locals=[];
    globals=[];
    $output=$('#output');
    $input=$('#input');
    inputs=[];
    commands=[];
    comTable = [];
    comTable['di'] = 'display';
    comTable['dis'] = 'display';
    comTable['disp'] = 'display';
    comTable['displ'] = 'display';
    comTable['displa'] = 'display';
    comTable['display'] = 'display';
    comTable['loc'] = 'local';
    comTable['loca'] = 'local';
    comTable['local'] = 'local';
    comTable['gl'] = 'global';
    comTable['glo'] = 'global';
    comTable['glob'] = 'global';
    comTable['globa'] = 'global';
    comTable['global'] = 'global';
    comTable['set']='set';
    comTable['g'] = 'generate';
    comTable['ge'] = 'generate';
    comTable['gen'] = 'generate';
    comTable['gene'] = 'generate';
    comTable['gener'] = 'generate';
    comTable['genera'] = 'generate';
    comTable['generat'] = 'generate';
    comTable['generate'] = 'generate';
    comTable['l']='list';
    comTable['li']='list';
    comTable['lis']='list';
    comTable['list']='list';
    comTable['forv']='forvalues';
    comTable['forva']='forvalues';
    comTable['forval']='forvalues';
    comTable['forvalu']='forvalues';
    comTable['forvalue']='forvalues';
    comTable['forvalues']='forvalues';
    comTable['}']='No Operation';
    opTable=[];
    opTable['display']=[];
    opTable['display']['_r']='_request';
    opTable['display']['_re']='_request';
    opTable['display']['_req']='_request';
    opTable['display']['_requ']='_request';
    opTable['display']['_reque']='_request';
    opTable['display']['_reques']='_request';
    opTable['display']['_request']='_request';
    opTable['set']=[];
    opTable['set']['ob']='obs';
    opTable['set']['obs']='obs';
});
$('button').click(function () {
    _N=0
    dataset=[];
    inputNum=0;
    inputs=$input.val().split('\n');
    $output.val('');
    locals=[];
    globals=[];
    var code = $('#code').val();
    commands = code.split('\n');
    var tokens = [];
    commands.forEach(function (entry) {
        tokens.push(entry.match(/(?:[^\s"]+|"[^"]*")+/g) );
    });
    var error = '';
    var nextIndex=0;
    $.each(tokens,function (index,entry) {
        if(nextIndex!==index){
            return true;
        }
        var tok = entry[0];
        entry[0] = comTable[tok];
        if (entry[0] === undefined) {
            error = tok + ' is not a recognized command';
            outputError(error);
            return false;
        }
        nextIndex+=execute(entry,index);
        if(!nextIndex){
            return false;
        }
    });
});

function execute(command,ind){
    switch(command[0]){
        case 'display':
            return executeDisplay(command);
        case 'local':
            return executeLocal(command);
        case 'global':
            return executeGlobal(command);
        case 'set':
            return executeSet(command);
        case 'generate':
            return executeGenerate(command);
        case 'list':
            return executeList(command);
        case 'forvalues':
            return executeForvalues(command,ind);
    }
}

function executeForvalues(command,ind){
    var re=/(\w+)=(.+)\((.+)\)(.+){/;
    var arr=re.exec(command[1]);
    if(arr==null){
        outputError('invalid format to command forvalues: '+command[1]);
        return false;
    }
    var locName=evaluate(arr[1],0);
    var i=Number(evaluate(arr[2],0));
    var increment=Number(evaluate(arr[3],0));
    var maximum=evaluate(arr[4],0);
    console.log(locName+' '+i+' '+increment+' '+maximum);
    maximum=Number(maximum);
    var curInd=ind+1;
    for(;i<=maximum;i+=increment){
        locals[locName]=i;
        globals['_'+locName]=i;
        for(curInd=ind+1;commands[curInd]!=='}';curInd++){
            var entry=commands[curInd].match(/(?:[^\s"]+|"[^"]*")+/g);
            var tok = entry[0];
            entry[0] = comTable[tok];
            if (entry[0] === undefined) {
                error = tok + ' is not a recognized command';
                outputError(error);
                return false;
            }
            console.log(entry);
            if(!execute(entry)){
                return false;
            }
            console.log($output.val());
        }
    }
    return curInd-ind;
}

function executeList(command){
    var out='\t'+Object.keys(dataset).join('\t')+'\n';
    for(var i=0;i<_N;i++){
        out+=(i+1)+'\t';
        Object.keys(dataset).forEach(function(element){
            out+=dataset[element][i]+'\t';
        })
        out+='\n';
    }
    $output.val(function(i,val){
        return val+out;
    });
    return 1;
}

function executeGenerate(command){
    var parts=command[1].split('=');
    dataset[parts[0]]=[];
    for(var i=0;i<_N;i++){
        dataset[parts[0]][i]=evaluateVariables(parts[1],i);
    }
    return 1;
}

function evaluateVariables(str,i){
    return eval(str.replace('_n',i+1));
}

function executeSet(command){
    if(opTable['set'][command[1]]=='obs'){
        _N=parseInt(command[2],10);
        return 1;
    }
    outputError('invalid option for command set: '+command[1]);
    return false;
}

function executeLocal(command){
    var parts=command[1].split('=');
    var name,value;
    if(parts.length==1){
        var re0=/^\+\+(\w+)$/;
        var re1=/^--(\w+)$/;
        var re2=/^(\w+)\+\+$/;
        var re3=/^(\w+)--$/;
        var arr=re0.exec(parts[0])||re1.exec(parts[0])||re2.exec(parts[0])||re3.exec(parts[0]);
        if(arr!=null){
            name=arr[1];
            if(parts[0].indexOf('-')>-1){
                value=globals[name]-1;
            }
            else{
                value=globals[name]+1;
            }
        }
        else{
            parts[1]=command[2];
        }
    }
    if(!value){
        value=evaluate(parts[1],0);
    }
    if(typeof value==='undefined'){
        return false;
    }
    if(!name){
        name=evaluate(parts[0]);
    }
    locals[name]=value;
    globals['_'+name]=value;
    return 1;
}

function executeGlobal(command){
    var parts=command[1].split('=');
    var name,value;
    if(parts.length==1){
        var re0=/^\+\+(\w+)$/;
        var re1=/^--(\w+)$/;
        var re2=/^(\w+)\+\+$/;
        var re3=/^(\w+)--$/;
        var arr=re0.exec(parts[0])||re1.exec(parts[0])||re2.exec(parts[0])||re3.exec(parts[0]);
        if(arr!=null){
            name=arr[1];
            if(parts[0].indexOf('-')>-1){
                value=globals[name]-1;
            }
            else{
                value=Number(globals[name])+1;
            }
        }
        else{
            parts[1]=command[2];
        }
    }
    if(!value){
        value=evaluate(parts[1],0);
    }
    if(typeof value==='undefined'){
        return false;
    }
    if(!name){
        name=evaluate(parts[0]);
    }
    if(name.charAt(0)=='_'){
        locals[name.substring(1)]=value;
    }
    globals[name]=value;
    return 1;
}

function executeDisplay(command){
    for(var i=1;i<command.length;i++){
        var comVal=command[i];
        $output.val(function(ind,val){
            var re=/^(\w+)/;
            var arr=re.exec(command[i]);
            if(arr!==null&&opTable['display'][arr[0]]=='_request'){
                re=/^\w+\((\w+)\)/;
                arr=re.exec(command[i]);
                var input=getInput();
                globals[arr[1]]=input;
                if(arr[1].charAt(0)=='_'){
                    locals[arr[1].substring(1)]=input;
                }
                return val;
            }
            return val+evaluate(command[i],0)+'\n';
        });
    }
    return 1;
}

function getInput(){
    var x=inputs[inputNum];
    inputNum++;
    return x;
}

function evaluate(str,captured){
    str=String(str);
    var index=str.indexOf('"');
    if(index==-1){
        return evaluate2(str);
    }
    var secondIndex=str.indexOf('"',index+1);
    while(secondIndex>0&&str.charAt(secondIndex-1)=='\\'){
        secondIndex=str.indexOf('"',secondIndex+1);
    }
    if(secondIndex<0){
        if(!captured){
            var error ='unmatched quotes';
            outputError(error);
            return undefined;
        }
        return '';
    }
    return (index>0?evaluate2(str.substring(0,index)):'')+evaluate2(str.substring(index,secondIndex+1))+(secondIndex<str.length-1?evaluate(str.substring(secondIndex)):'');
}

function evaluate2(str){
    var index=str.indexOf('`');
    if(index==-1){
        return evaluate3(str);
    }
    var secondIndex=str.indexOf('\'',index+1);
    while(secondIndex>0&&str.charAt(secondIndex-1)=='\\'){
        secondIndex=str.indexOf('\'',secondIndex+1);
    }
    if(secondIndex<0){
        return evaluate3(str);
    }
    var value=locals[str.substring(index+1,secondIndex)];
    if(typeof value==='undefined'){
        value='';
    }
    return evaluate((index>0?str.substring(0,index):'')+value+(secondIndex<str.length-1?str.substring(secondIndex+1):''));
}

function evaluate3(str){
    var re=/\$(\w+)/;
    var arr=re.exec(str);
    if(arr!==null){
        var index=arr.index;
        var length=arr[0].length;
        var value=globals[arr[1]];
        str=str.substring(0,index)+value+str.substring(index+length);
        return evaluate(str);
    }
    try {
        var value=eval(str.replace('_N',_N));
        return value;
    }catch(err){
        console.log(str);
        return str;
    }
}

function evaluate4(str){
    try {
        var value=eval(str);
        return value;
    }catch(err){
        console.log(str);
        return undefined;
    }
}

function outputError(error) {
    $output.val(function(ind,val){
        return val+error+'\n';
    });
}
</script>
</body>
</html>

Edit: added replace and checks for generate.

<html>
<body>
Input
<textarea id="input"></textarea>
<br/>
Code
<textarea id="code"></textarea>
<br/>
<button>Run</button>
<br/>Output:
<textarea id="output"></textarea>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">

$(function(){
    _N=0
    dataset=[];
    locals=[];
    globals=[];
    $output=$('#output');
    $input=$('#input');
    inputs=[];
    commands=[];
    comTable = [];
    comTable['di'] = 'display';
    comTable['dis'] = 'display';
    comTable['disp'] = 'display';
    comTable['displ'] = 'display';
    comTable['displa'] = 'display';
    comTable['display'] = 'display';
    comTable['loc'] = 'local';
    comTable['loca'] = 'local';
    comTable['local'] = 'local';
    comTable['gl'] = 'global';
    comTable['glo'] = 'global';
    comTable['glob'] = 'global';
    comTable['globa'] = 'global';
    comTable['global'] = 'global';
    comTable['set']='set';
    comTable['g'] = 'generate';
    comTable['ge'] = 'generate';
    comTable['gen'] = 'generate';
    comTable['gene'] = 'generate';
    comTable['gener'] = 'generate';
    comTable['genera'] = 'generate';
    comTable['generat'] = 'generate';
    comTable['generate'] = 'generate';
    comTable['replace'] = 'replace';
    comTable['l']='list';
    comTable['li']='list';
    comTable['lis']='list';
    comTable['list']='list';
    comTable['forv']='forvalues';
    comTable['forva']='forvalues';
    comTable['forval']='forvalues';
    comTable['forvalu']='forvalues';
    comTable['forvalue']='forvalues';
    comTable['forvalues']='forvalues';
    comTable['}']='No Operation';
    opTable=[];
    opTable['display']=[];
    opTable['display']['_r']='_request';
    opTable['display']['_re']='_request';
    opTable['display']['_req']='_request';
    opTable['display']['_requ']='_request';
    opTable['display']['_reque']='_request';
    opTable['display']['_reques']='_request';
    opTable['display']['_request']='_request';
    opTable['set']=[];
    opTable['set']['ob']='obs';
    opTable['set']['obs']='obs';
});
$('button').click(function () {
    _N=0
    dataset=[];
    inputNum=0;
    inputs=$input.val().split('\n');
    $output.val('');
    locals=[];
    globals=[];
    var code = $('#code').val();
    commands = code.split('\n');
    var tokens = [];
    commands.forEach(function (entry) {
        tokens.push(entry.match(/(?:[^\s"]+|"[^"]*")+/g) );
    });
    var error = '';
    var nextIndex=0;
    $.each(tokens,function (index,entry) {
        if(nextIndex!==index){
            return true;
        }
        var tok = entry[0];
        entry[0] = comTable[tok];
        if (entry[0] === undefined) {
            error = tok + ' is not a recognized command';
            outputError(error);
            return false;
        }
        nextIndex+=execute(entry,index);
        if(!nextIndex){
            return false;
        }
    });
});

function execute(command,ind){
    switch(command[0]){
        case 'display':
            return executeDisplay(command);
        case 'local':
            return executeLocal(command);
        case 'global':
            return executeGlobal(command);
        case 'set':
            return executeSet(command);
        case 'generate':
            return executeGenerate(command);
        case 'replace':
            return executeReplace(command);
        case 'list':
            return executeList(command);
        case 'forvalues':
            return executeForvalues(command,ind);
    }
}

function executeForvalues(command,ind){
    var re=/(\w+)=(.+)\((.+)\)(.+){/;
    var arr=re.exec(command[1]);
    if(arr==null){
        outputError('invalid format to command forvalues: '+command[1]);
        return false;
    }
    var locName=evaluate(arr[1],0);
    var i=Number(evaluate(arr[2],0));
    var increment=Number(evaluate(arr[3],0));
    var maximum=evaluate(arr[4],0);
    console.log(locName+' '+i+' '+increment+' '+maximum);
    maximum=Number(maximum);
    var curInd=ind+1;
    for(;i<=maximum;i+=increment){
        locals[locName]=i;
        globals['_'+locName]=i;
        for(curInd=ind+1;commands[curInd]!=='}';curInd++){
            var entry=commands[curInd].match(/(?:[^\s"]+|"[^"]*")+/g);
            var tok = entry[0];
            entry[0] = comTable[tok];
            if (entry[0] === undefined) {
                error = tok + ' is not a recognized command';
                outputError(error);
                return false;
            }
            console.log(entry);
            if(!execute(entry)){
                return false;
            }
            console.log($output.val());
        }
    }
    return curInd-ind;
}

function executeList(command){
    var out='\t'+Object.keys(dataset).join('\t')+'\n';
    for(var i=0;i<_N;i++){
        out+=(i+1)+'\t';
        Object.keys(dataset).forEach(function(element){
            out+=dataset[element][i]===undefined?'.':dataset[element][i]+'\t';
        })
        out+='\n';
    }
    $output.val(function(i,val){
        return val+out;
    });
    return 1;
}

function executeGenerate(command){
    var parts=command[1].split('=');
    if(dataset[parts[0]]){
        outputError('variable '+parts[0]+' already exists.');
        return false;
    }
    dataset[parts[0]]=[];
    for(var i=0;i<_N;i++){
        dataset[parts[0]][i]=evaluateVariables(parts[1],i);
    }
    return 1;
}

function executeReplace(command){
    var parts=command[1].split('=');
    if(!dataset[parts[0]]){
        outputError('variable '+parts[0]+' does not exist.');
        return false;
    }
    for(var i=0;i<_N;i++){
        dataset[parts[0]][i]=evaluateVariables(parts[1],i);
    }
    return 1;
}

function evaluateVariables(str,i){
    return eval(str.replace('_n',i+1));
}

function executeSet(command){
    if(opTable['set'][command[1]]=='obs'){
        _N=parseInt(command[2],10);
        return 1;
    }
    outputError('invalid option for command set: '+command[1]);
    return false;
}

function executeLocal(command){
    var parts=command[1].split('=');
    var name,value;
    if(parts.length==1){
        var re0=/^\+\+(\w+)$/;
        var re1=/^--(\w+)$/;
        var re2=/^(\w+)\+\+$/;
        var re3=/^(\w+)--$/;
        var arr=re0.exec(parts[0])||re1.exec(parts[0])||re2.exec(parts[0])||re3.exec(parts[0]);
        if(arr!=null){
            name=arr[1];
            if(parts[0].indexOf('-')>-1){
                value=globals[name]-1;
            }
            else{
                value=globals[name]+1;
            }
        }
        else{
            parts[1]=command[2];
        }
    }
    if(!value){
        value=evaluate(parts[1],0);
    }
    if(typeof value==='undefined'){
        return false;
    }
    if(!name){
        name=evaluate(parts[0]);
    }
    locals[name]=value;
    globals['_'+name]=value;
    return 1;
}

function executeGlobal(command){
    var parts=command[1].split('=');
    var name,value;
    if(parts.length==1){
        var re0=/^\+\+(\w+)$/;
        var re1=/^--(\w+)$/;
        var re2=/^(\w+)\+\+$/;
        var re3=/^(\w+)--$/;
        var arr=re0.exec(parts[0])||re1.exec(parts[0])||re2.exec(parts[0])||re3.exec(parts[0]);
        if(arr!=null){
            name=arr[1];
            if(parts[0].indexOf('-')>-1){
                value=globals[name]-1;
            }
            else{
                value=Number(globals[name])+1;
            }
        }
        else{
            parts[1]=command[2];
        }
    }
    if(!value){
        value=evaluate(parts[1],0);
    }
    if(typeof value==='undefined'){
        return false;
    }
    if(!name){
        name=evaluate(parts[0]);
    }
    if(name.charAt(0)=='_'){
        locals[name.substring(1)]=value;
    }
    globals[name]=value;
    return 1;
}

function executeDisplay(command){
    for(var i=1;i<command.length;i++){
        var comVal=command[i];
        $output.val(function(ind,val){
            var re=/^(\w+)/;
            var arr=re.exec(command[i]);
            if(arr!==null&&opTable['display'][arr[0]]=='_request'){
                re=/^\w+\((\w+)\)/;
                arr=re.exec(command[i]);
                var input=getInput();
                globals[arr[1]]=input;
                if(arr[1].charAt(0)=='_'){
                    locals[arr[1].substring(1)]=input;
                }
                return val;
            }
            return val+evaluate(command[i],0)+'\n';
        });
    }
    return 1;
}

function getInput(){
    var x=inputs[inputNum];
    inputNum++;
    return x;
}

function evaluate(str,captured){
    str=String(str);
    var index=str.indexOf('"');
    if(index==-1){
        return evaluate2(str);
    }
    var secondIndex=str.indexOf('"',index+1);
    while(secondIndex>0&&str.charAt(secondIndex-1)=='\\'){
        secondIndex=str.indexOf('"',secondIndex+1);
    }
    if(secondIndex<0){
        if(!captured){
            var error ='unmatched quotes';
            outputError(error);
            return undefined;
        }
        return '';
    }
    return (index>0?evaluate2(str.substring(0,index)):'')+evaluate2(str.substring(index,secondIndex+1))+(secondIndex<str.length-1?evaluate(str.substring(secondIndex)):'');
}

function evaluate2(str){
    var index=str.indexOf('`');
    if(index==-1){
        return evaluate3(str);
    }
    var secondIndex=str.indexOf('\'',index+1);
    while(secondIndex>0&&str.charAt(secondIndex-1)=='\\'){
        secondIndex=str.indexOf('\'',secondIndex+1);
    }
    if(secondIndex<0){
        return evaluate3(str);
    }
    var value=locals[str.substring(index+1,secondIndex)];
    if(typeof value==='undefined'){
        value='';
    }
    return evaluate((index>0?str.substring(0,index):'')+value+(secondIndex<str.length-1?str.substring(secondIndex+1):''));
}

function evaluate3(str){
    var re=/\$(\w+)/;
    var arr=re.exec(str);
    if(arr!==null){
        var index=arr.index;
        var length=arr[0].length;
        var value=globals[arr[1]];
        str=str.substring(0,index)+value+str.substring(index+length);
        return evaluate(str);
    }
    try {
        var value=eval(str.replace('_N',_N));
        return value;
    }catch(err){
        console.log(str);
        return str;
    }
}

function evaluate4(str){
    try {
        var value=eval(str);
        return value;
    }catch(err){
        console.log(str);
        return undefined;
    }
}

function outputError(error) {
    $output.val(function(ind,val){
        return val+error+'\n';
    });
}
</script>
</body>
</html>
Source Link
bmarks
  • 2.1k
  • 11
  • 13

STATA

Has support for some parts of display, forvalues, list, generate, and set obs. In addition, it has some supports for macro (STATA's variables) creation and use. It supports enough operations for some of the simpler answers that have been posted on this site, such as http://codegolf.stackexchange.com/questions/40376/evolution-of-hello-world/40406?s=4|0.2560#40406, http://codegolf.stackexchange.com/questions/44949/generate-the-st%c3%b6hr-sequence/44999?s=2|0.5123#44999, http://codegolf.stackexchange.com/questions/35862/make-me-an-alphabet-tree/35869?s=5|0.2288#35869 (replace single quotes with double quotes and make it 3 lines instead of 1). This is a work in progress, and I hope to continue it soon, but I figured I would at least put something here for now.

<html>
<body>
Input
<textarea id="input"></textarea>
<br/>
Code
<textarea id="code"></textarea>
<br/>
<button>Run</button>
<br/>Output:
<textarea id="output"></textarea>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">

$(function(){
    _N=0
    dataset=[];
    locals=[];
    globals=[];
    $output=$('#output');
    $input=$('#input');
    inputs=[];
    commands=[];
    comTable = [];
    comTable['di'] = 'display';
    comTable['dis'] = 'display';
    comTable['disp'] = 'display';
    comTable['displ'] = 'display';
    comTable['displa'] = 'display';
    comTable['display'] = 'display';
    comTable['loc'] = 'local';
    comTable['loca'] = 'local';
    comTable['local'] = 'local';
    comTable['gl'] = 'global';
    comTable['glo'] = 'global';
    comTable['glob'] = 'global';
    comTable['globa'] = 'global';
    comTable['global'] = 'global';
    comTable['set']='set';
    comTable['g'] = 'generate';
    comTable['ge'] = 'generate';
    comTable['gen'] = 'generate';
    comTable['gene'] = 'generate';
    comTable['gener'] = 'generate';
    comTable['genera'] = 'generate';
    comTable['generat'] = 'generate';
    comTable['generate'] = 'generate';
    comTable['l']='list';
    comTable['li']='list';
    comTable['lis']='list';
    comTable['list']='list';
    comTable['forv']='forvalues';
    comTable['forva']='forvalues';
    comTable['forval']='forvalues';
    comTable['forvalu']='forvalues';
    comTable['forvalue']='forvalues';
    comTable['forvalues']='forvalues';
    comTable['}']='No Operation';
    opTable=[];
    opTable['display']=[];
    opTable['display']['_r']='_request';
    opTable['display']['_re']='_request';
    opTable['display']['_req']='_request';
    opTable['display']['_requ']='_request';
    opTable['display']['_reque']='_request';
    opTable['display']['_reques']='_request';
    opTable['display']['_request']='_request';
    opTable['set']=[];
    opTable['set']['ob']='obs';
    opTable['set']['obs']='obs';
});
$('button').click(function () {
    _N=0
    dataset=[];
    inputNum=0;
    inputs=$input.val().split('\n');
    $output.val('');
    locals=[];
    globals=[];
    var code = $('#code').val();
    commands = code.split('\n');
    var tokens = [];
    commands.forEach(function (entry) {
        tokens.push(entry.match(/(?:[^\s"]+|"[^"]*")+/g) );
    });
    var error = '';
    var nextIndex=0;
    $.each(tokens,function (index,entry) {
        if(nextIndex!==index){
            return true;
        }
        var tok = entry[0];
        entry[0] = comTable[tok];
        if (entry[0] === undefined) {
            error = tok + ' is not a recognized command';
            outputError(error);
            return false;
        }
        nextIndex+=execute(entry,index);
        if(!nextIndex){
            return false;
        }
    });
});

function execute(command,ind){
    switch(command[0]){
        case 'display':
            return executeDisplay(command);
        case 'local':
            return executeLocal(command);
        case 'global':
            return executeGlobal(command);
        case 'set':
            return executeSet(command);
        case 'generate':
            return executeGenerate(command);
        case 'list':
            return executeList(command);
        case 'forvalues':
            return executeForvalues(command,ind);
    }
}

function executeForvalues(command,ind){
    var re=/(\w+)=(.+)\((.+)\)(.+){/;
    var arr=re.exec(command[1]);
    if(arr==null){
        outputError('invalid format to command forvalues: '+command[1]);
        return false;
    }
    var locName=evaluate(arr[1],0);
    var i=Number(evaluate(arr[2],0));
    var increment=Number(evaluate(arr[3],0));
    var maximum=evaluate(arr[4],0);
    console.log(locName+' '+i+' '+increment+' '+maximum);
    maximum=Number(maximum);
    var curInd=ind+1;
    for(;i<=maximum;i+=increment){
        locals[locName]=i;
        globals['_'+locName]=i;
        for(curInd=ind+1;commands[curInd]!=='}';curInd++){
            var entry=commands[curInd].match(/(?:[^\s"]+|"[^"]*")+/g);
            var tok = entry[0];
            entry[0] = comTable[tok];
            if (entry[0] === undefined) {
                error = tok + ' is not a recognized command';
                outputError(error);
                return false;
            }
            console.log(entry);
            if(!execute(entry)){
                return false;
            }
            console.log($output.val());
        }
    }
    return curInd-ind;
}

function executeList(command){
    var out='\t'+Object.keys(dataset).join('\t')+'\n';
    for(var i=0;i<_N;i++){
        out+=(i+1)+'\t';
        Object.keys(dataset).forEach(function(element){
            out+=dataset[element][i]+'\t';
        })
        out+='\n';
    }
    $output.val(function(i,val){
        return val+out;
    });
    return 1;
}

function executeGenerate(command){
    var parts=command[1].split('=');
    dataset[parts[0]]=[];
    for(var i=0;i<_N;i++){
        dataset[parts[0]][i]=evaluateVariables(parts[1],i);
    }
    return 1;
}

function evaluateVariables(str,i){
    return eval(str.replace('_n',i+1));
}

function executeSet(command){
    if(opTable['set'][command[1]]=='obs'){
        _N=parseInt(command[2],10);
        return 1;
    }
    outputError('invalid option for command set: '+command[1]);
    return false;
}

function executeLocal(command){
    var parts=command[1].split('=');
    var name,value;
    if(parts.length==1){
        var re0=/^\+\+(\w+)$/;
        var re1=/^--(\w+)$/;
        var re2=/^(\w+)\+\+$/;
        var re3=/^(\w+)--$/;
        var arr=re0.exec(parts[0])||re1.exec(parts[0])||re2.exec(parts[0])||re3.exec(parts[0]);
        if(arr!=null){
            name=arr[1];
            if(parts[0].indexOf('-')>-1){
                value=globals[name]-1;
            }
            else{
                value=globals[name]+1;
            }
        }
        else{
            parts[1]=command[2];
        }
    }
    if(!value){
        value=evaluate(parts[1],0);
    }
    if(typeof value==='undefined'){
        return false;
    }
    if(!name){
        name=evaluate(parts[0]);
    }
    locals[name]=value;
    globals['_'+name]=value;
    return 1;
}

function executeGlobal(command){
    var parts=command[1].split('=');
    var name,value;
    if(parts.length==1){
        var re0=/^\+\+(\w+)$/;
        var re1=/^--(\w+)$/;
        var re2=/^(\w+)\+\+$/;
        var re3=/^(\w+)--$/;
        var arr=re0.exec(parts[0])||re1.exec(parts[0])||re2.exec(parts[0])||re3.exec(parts[0]);
        if(arr!=null){
            name=arr[1];
            if(parts[0].indexOf('-')>-1){
                value=globals[name]-1;
            }
            else{
                value=Number(globals[name])+1;
            }
        }
        else{
            parts[1]=command[2];
        }
    }
    if(!value){
        value=evaluate(parts[1],0);
    }
    if(typeof value==='undefined'){
        return false;
    }
    if(!name){
        name=evaluate(parts[0]);
    }
    if(name.charAt(0)=='_'){
        locals[name.substring(1)]=value;
    }
    globals[name]=value;
    return 1;
}

function executeDisplay(command){
    for(var i=1;i<command.length;i++){
        var comVal=command[i];
        $output.val(function(ind,val){
            var re=/^(\w+)/;
            var arr=re.exec(command[i]);
            if(arr!==null&&opTable['display'][arr[0]]=='_request'){
                re=/^\w+\((\w+)\)/;
                arr=re.exec(command[i]);
                var input=getInput();
                globals[arr[1]]=input;
                if(arr[1].charAt(0)=='_'){
                    locals[arr[1].substring(1)]=input;
                }
                return val;
            }
            return val+evaluate(command[i],0)+'\n';
        });
    }
    return 1;
}

function getInput(){
    var x=inputs[inputNum];
    inputNum++;
    return x;
}

function evaluate(str,captured){
    str=String(str);
    var index=str.indexOf('"');
    if(index==-1){
        return evaluate2(str);
    }
    var secondIndex=str.indexOf('"',index+1);
    while(secondIndex>0&&str.charAt(secondIndex-1)=='\\'){
        secondIndex=str.indexOf('"',secondIndex+1);
    }
    if(secondIndex<0){
        if(!captured){
            var error ='unmatched quotes';
            outputError(error);
            return undefined;
        }
        return '';
    }
    return (index>0?evaluate2(str.substring(0,index)):'')+evaluate2(str.substring(index,secondIndex+1))+(secondIndex<str.length-1?evaluate(str.substring(secondIndex)):'');
}

function evaluate2(str){
    var index=str.indexOf('`');
    if(index==-1){
        return evaluate3(str);
    }
    var secondIndex=str.indexOf('\'',index+1);
    while(secondIndex>0&&str.charAt(secondIndex-1)=='\\'){
        secondIndex=str.indexOf('\'',secondIndex+1);
    }
    if(secondIndex<0){
        return evaluate3(str);
    }
    var value=locals[str.substring(index+1,secondIndex)];
    if(typeof value==='undefined'){
        value='';
    }
    return evaluate((index>0?str.substring(0,index):'')+value+(secondIndex<str.length-1?str.substring(secondIndex+1):''));
}

function evaluate3(str){
    var re=/\$(\w+)/;
    var arr=re.exec(str);
    if(arr!==null){
        var index=arr.index;
        var length=arr[0].length;
        var value=globals[arr[1]];
        str=str.substring(0,index)+value+str.substring(index+length);
        return evaluate(str);
    }
    try {
        var value=eval(str.replace('_N',_N));
        return value;
    }catch(err){
        console.log(str);
        return str;
    }
}

function evaluate4(str){
    try {
        var value=eval(str);
        return value;
    }catch(err){
        console.log(str);
        return undefined;
    }
}

function outputError(error) {
    $output.val(function(ind,val){
        return val+error+'\n';
    });
}
</script>
</body>
</html>