JavaScript: my 2007 Language of the Year

I’m sure many of you have heard of the “Language of the Year”:http://www.pragmaticprogrammer.com/loty/ idea. I’ve done it in the past, with minor success. I usually get caught in other things by May or June and soon forget about it.

I didn’t plan on JavaScript being my LotY — it just sort of happened. At my new position, I’m surrounded by poorly written JavaScript that is interfacing with different web pages. Changed that JavaScript code has been a pain. I’ve searched around the web for different help and caught some ideas - some good and some bad. I then have spent some money on JavaScript: The Definitive Guide and that has gotten me to see JavaScript in a whole new light. I’m beginning to see what Blaine told me once — it’s really just Lisp.

Anyway, here is a function that does my normal first task when learning a new language — the “The Sieve of Erastothenes”:http://mathforum.org/dr.math/faq/faq.prime.num.html . This was harder than it has been in other languages I’ve recently learned because JavaScript does not have a built-in method on the array that returns the index of an object in the array. So the code was a bit longer, but somewhat more interesting. This worked fine in “Spidermonkey”:http://www.mozilla.org/js/spidermonkey/ .

    
        function sieve(upper) {

          var primes = new Array();
          var composites = new Array();

          for (var num=2; num< =upper; num++) {

              var found=false;
              for( var i in composites){ 
                  if (composites[i]==num) {
                      found=true;
                      break;
                  }
              }

              if (!found) {
                  primes.push(num);

                  for (var k=num*2; k<=upper; k+=num) {
                      composites.push(k);
                  }
              }

          }

          print(primes);

        }


    

Leave a Reply

You must be logged in to post a comment.