javascript speed test

Aside

given the following function:

  function addInts(anArray){
     var result = 0;
     for (var i = 0; i < anArray.length; ++i){
        if (anArray[i] < 21) {
           result = result + anArray[i];
        } else { 
           result = result + anArray[i] - 21;
        }
     }
     return result;
  }

what would you expect will run faster?

    addInts(sortedArray); #sorted
    addInts(unsortedArray); #unsorted

 


 
check your answer


 

[More programming riddles]

javascript anagram detector

Aside

what’s the shortest anagram detector you know how to write, in javascript?


there must be a shorter way to do this. highlight below to see a solution.


var anagramDetector = function (x,y) {
   if (x.length != y.length) return false;
   var alpha_x = x.split("").sort().join("");
   var alpha_y = y.split("").sort().join("");
   for ( j = 0; j<y.length;++j) {
       if (alpha_x[j] != alpha_y[j]) return false;
  }
  return true;
}

PS: there’s a cool method for solving this for a fixed alphabet, using primes


[More programming riddles]

javascript speed test

Aside

if you had to guess, which of the following two bits of javascript code would you say executes faster?

Exhibit A:

var keys = Object.keys(MyObj); //cloning the key array
var length = keys.length;
for (var i = 0; i < length; i++) {
  var val = MyObj[keys[i]];
};

Exhibit B:

for (var key in MyObj) {
 if (MyObj.hasOwnProperty(key)) { //hasOwnProperty is a native function
  var val = MyObj[key];
 }
}

Check your answer.


[More programming riddles]

 

 

 


this is what things looked like last year in september, with an up to date version of chrome:

Screen Shot 2013-09-17 at 7.04.32 PM

null vs. undefined (javascript)

Aside

how well do you know your “null”s and “undefined”s?

write down what you expect the result of each operation to be. run them in a javascript console (ChromeFirefox/FirebugSafari). compare, verify, contrast, and, for fun, give yourself a score out of “3/4 donut”.

// Equality
null == undefined
null === undefined
!null == !undefined
!null === !undefined

// addition and concatenation
null + ''
undefined + ''
null + 1
undefined + 1

// fun with enumerations
test = []; test.push(null); console.log(test)
test = []; test.push(undefined); console.log(test)
{null:2}
{undefined:2}
{a:null}
{a:undefined}

[More programming riddles]

wtf javascript

Aside

javascript riddle time.

say that you’ve ventured into the land of XmlHTTPRequest ( $.ajax calls for the jquery people), and you’ve heard through the grapevine that (gasp!) it may be possible to make cross-domain http calls with this tool.

excitement! if you’re like me, you’ll see a chance to hack in fixes for a myriad of small bits of javascript you have lying around. so, off you’ll go, merrily trying anything that might work – your initial code might even look something like this, if you’re used to jquery:

  request = $.ajax({
        type: "POST", // !? - request sent through as HTTP GET
        url: 'http://someotherdomain.com/,
        data: 'some data',
        async: true,
        cache: false,
        dataType: 'jsonp',
        crossDomain: true,
        xhrFields: {
	       withCredentials: true //share cookies across domains!
	},
  });
  request.abort(); // !? - does nothing

confused


ok, so, technically this is a wtf jquery, more so than a wtf javascript. ‘jsonp’ crossdomain requests aren’t currently supported, natively, by most browsers – a native implementation would take significant care to avoid being a security risk (i’m not entirely sure it’s possible, even). there is, though, a fairly generic hack for implementing them. take a look at jquery-jsonp, which is close to the state of the art of what’s possible nowadays, and you’ll even see it there:

  // Create the script tag
  script = $( STR_SCRIPT_TAG )[ 0 ];
  script.id = STR_JQUERY_JSONP + count++;
  
  ...

  // Set source
  script.src = url;

create a new script tag, with the source set to be the target of your jsonp request, dynamically add it to the document tree, and wrap it in event handlers to handle the response or any errors.

since it’s a html script tag, it always leads to a browser HTTP GET request; and, since the request is initiated indirectly, by adding the tag to the document tree, some of the usual niceties for XmlHTTPRequest aren’t available – eg, the ability to interrupt.

mystery demystified – the behaviour is correct, though still unpleasantly surprising to me


[More programming riddles]