tags:

views:

69

answers:

3

I came across following code

function currentSlideFromParams() {
  var result;
  if (result = window.location.hash.match(/#([0-9]+)/)) {
    return result[result.length - 1] - 1;
  }
}

It is clear that this code is written by a ruby developer. However what is ruby idiomatic is not necessarily JavaScript idiom. Secondly the code complains when I run through Jslint because it warns about having an assignment inside conditional check.

Please suggest refactored code that is as per JavaScript idiom.

+2  A: 

Just take the variable assignment out of the if() statement.

function currentSlideFromParams() {
  var result = window.location.hash.match(/#([0-9]+)/);
  if (result) {
    return result[result.length - 1] - 1;
  }
}

Also, if you anticipate multiple matches and are looking for the last, you should add the g global identifier to the regex.

window.location.hash.match(/#([0-9]+)/g)
patrick dw
+4  A: 
function currentSlideFromParams() {
  var result = window.location.hash.match(/#([0-9]+)/);
  if (result ) {
    return result[result.length - 1] - 1;
  }
}

This would assign it first. I don't see what the big deal is, though.. you don't really have to obey jslint's rules.

meder
one does not have to but it catches a lot of errors. Also it bring conformity in the team so that one guy add ; and one does not add ;. now jQuery has started running its code through jslint too.
Nadal
A: 

It is clear that this code is written by a ruby developer.

Really? A rubyist would write:

def current_slide_from_params
  (location.hash =~ /#(\d+)/ && $1).to_i - 1
end

which translates to:

function currentSlideFromParams() {
  return (/#(\d+)/.test(location.hash) && RegExp.$1) - 1;
}

;)

matyr