开发者

javascript written by ruby developer. needs refactoring

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 wha开发者_C百科t 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.


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.


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)


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;
}

;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜