Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript regexp performance.

I have a function that corrects capitalization for a list of unusually capitalized words:

var line = "some long string of text";
["AppleScript", "Bluetooth", "DivX", "FireWire", "GarageBand", 
 "iPhone", "iTunes", "iWeb", "iWork", "JavaScript", "jQuery", "MacBook", 
 "MySQL", "PowerBook", "PowerPoint", "QuickTime", "TextEdit", "TextMate",
 // ... 
 "Wi-Fi", "Xcode", "Xserve", "XMLHttpRequest"].forEach(function(name) {
      line = line.replace(RegExp(name, "gi"), name);
});

Now the problem I am facing is that most input strings will contain on average between 0 and 3 of these words. Obviously now I am doing dozens (and potentially hundreds; that array has an uncanny tendency to grow over time) of function calls which essentially do nothing.

How can I make this code faster and get rid of the unnecessary function calls?

Example input:

My iphone application has a user form under UIViewController. When I start application again some of my UIView changes its positions and sizes. (These UIViews depend on keyboard position) Somewhere is definitely my fault. I try to figure what is going on when application starts again from background and where the UIView changes can be done.

like image 232
Jakub Hampl Avatar asked Mar 16 '11 11:03

Jakub Hampl


1 Answers

You can build regexp containing all your words, capturing each word by enclosing it in parentheses. Using that in a replace will provide enough information to recover the original word in the replace function.

  function correct (text, words) {
    return text.replace (RegExp ('\\b(?:(' + words.join (')|(') + '))\\b', 'ig'), function (m) {
      for (var a = arguments.length - 2; a--;)
        if (arguments[a])
      return words[a-1] || m;
    });
  } 

  console.log (correct ("My iphone itunes divx firewire application has a user form under uiviewcontroller. When I start application again some of my uiview changes its positions and sizes. (These uiviews depend on keyboard position) Somewhere is definitely my fault. I try to figure what is going on when application starts again from background and where the uiview changes can be done.",
    ["AppleScript", "Bluetooth", "DivX", "FireWire", "GarageBand", 
 "iPhone", "iTunes", "iWeb", "iWork", "JavaScript", "jQuery", "MacBook", 
 "MySQL", "PowerBook", "PowerPoint", "QuickTime", "TextEdit", "TextMate",
 // ... 
 "UIViewController","UIView",
 "Wi-Fi", "Xcode", "Xserve", "XMLHttpRequest"]));
My iPhone iTunes DivX FireWire application has a user form under UIViewController. When I start application again some of my UIView changes its positions and sizes. (These UIViews depend on keyboard position) Somewhere is definitely my fault. I try to figure what is going on when application starts again from background and where the UIView changes can be done.

This turns out to be faster then the original code.

like image 71
HBP Avatar answered Sep 21 '22 21:09

HBP