0
\$\begingroup\$

I wrote this small test, i would love to know if it's possible to achieve the same result in a more "efficient" way, before any moderator closes this question, it's not subjective because my defention of efficient here means less lines of code, and less memory usage.

Here is a Demo : http://jsfiddle.net/YsjLp/

and here is the JS code :

var position = 0;
var divToEdit = document.getElementById('here');

function executeIt(){
    setInterval(function(){moveIt()},300);  
}

function moveIt(){
    var textToInsert = '';
    var textLength = 10;

    for (var i = 0; i <= textLength; i++) {     

        if(i == position){                      
            textToInsert += '[-]';      
        }else{
            textToInsert += '-';    
        }       
    };  

    if(position == textLength){
        position = 0;
    }else{
        position += 1;
    }

    divToEdit.innerHTML = textToInsert;
}   

executeIt();
\$\endgroup\$

migrated from stackoverflow.com Sep 18 '13 at 14:33

This question came from our site for professional and enthusiast programmers.

  • \$\begingroup\$ Is there even a question here? \$\endgroup\$ – user25057 Sep 4 '13 at 5:36
  • \$\begingroup\$ @remyabel yes, the question is, could the above code be rewritten in a more efficient way, efficient defined in the question body. \$\endgroup\$ – Taleb Elem Sep 4 '13 at 5:38
1
\$\begingroup\$

As you define efficient to be "less lines of code", here it is:

function moveIt(){
    var textToInsert = '';
    var textLength = 10;

    for (var i = 0; i <= textLength; i++)
        textToInsert+= (i==position)?'[-]':'-';
    (position==textLength)?position=0:position++;
    divToEdit.innerHTML = textToInsert;
}

Demo: http://jsfiddle.net/YsjLp/3/

\$\endgroup\$
  • \$\begingroup\$ Fair enough, a good use of ternary operators, i would love to see both benchmarked, i'll check and see, thank you. \$\endgroup\$ – Taleb Elem Sep 4 '13 at 21:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy