2011-03-16 14 views
5

나는 비정상적으로 대문자로 된 단어들의 목록을 대문자로 바꿔주는 함수를 가지고있다 :자바 스크립트 정규식 성능.

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

이제 내가 직면하고있는 문제는 대부분의 입력 문자열이이 단어들 중 0과 3 사이의 평균을 포함한다는 것이다. 분명히 지금은 본질적으로 아무 것도하지 않는 함수 호출을 수십 개 (잠재적으로 수백 개, 배열은 시간이 지남에 따라 성장하는 기괴한 경향이 있습니다)하고 있습니다.

이 코드를 더 빠르게 만들 수 있으며 불필요한 함수 호출을 제거 할 수 있습니까?

예제 입력 :

내 아이폰 응용 프로그램 UIViewController에서 사용자 양식이 있습니다. 다시 응용 프로그램을 시작하면 UIView의 위치와 크기가 변경됩니다. (이러한 UIView는 키보드 위치에 따라 달라집니다.) 어딘가에 분명히 내 잘못이 있습니다. 백그라운드에서 응용 프로그램이 다시 시작되고 UIView 변경 사항을 수행 할 수있는 경우 진행되는 상황을 파악하려고합니다.

+0

통화가 불필요하지 않은가요? 각 문자열을 대문자로 표시하려면 각 문자열을 확인해야합니다. 존재하지 않기 때문에 검사가 필요하지 않다는 것을 의미하지는 않습니다 ... –

+0

@Sam하지만 전체 입력? 아니면 하나의 함수 호출로 모든 검사를 수행하는 똑똑한 정규 표현식을 만들 수 있습니까? –

+0

나는 너의 요점을 보았다. –

답변

5

모든 단어가 포함 된 regexp를 빌드하고 각 단어를 괄호로 묶어서 캡처 할 수 있습니다. 대체에서 해당 단어를 사용하면 대체 기능에서 원래 단어를 복구 할 수있는 충분한 정보를 얻을 수 있습니다.

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.

+0

이제 제가 지금 가지고있는 코드가 빠를 것입니까? 왜? –

+0

이 함수 호출 수는 2 + (number_of_words_replaced)입니다. 무거운 리프트의 나머지 부분은 빠른 내부 기능으로 수행됩니다. words 배열이 정적 인 경우 각 호출에서 regexp 빌드를 제거 할 수 있습니다 – HBP

+1

regexp는 다음 단어들과 일치하기 때문에 약간 수정해야합니다 :'RegExp ('\\ b (? :('+ words.join (') | (') +')) \\ b ','ig ')'트릭을합니다. –