When I first saw the topic I thought:
"Oh no.. , not another entire script to simply swap a string from left to right " (as you can do that in one line of code, see below). But I must say, I am pleasantly surprised to see you took it a step further with a twist (almost literally
).
Anyways...
The whole process to replace a character with another in OnEvent_ChatWndSendMessage() can already be made more efficient if you integrate the second 'For' loop (line 74) into the first (line 62).
At this moment you do:
- iterate thru the original string and replace character x with y
- iterate thru the new string and flip it left to right.
This means 2 times iterating thru the entire string.
Together with that you also look up a part of the string deep inside the loop each time to build your new string (and even two times: the stuff which is in front of the replaced character, and the stuff which comes after it), this is very slow and not needed.
All you need is the actual new character in the loop. Do the concatenation later, after the whole loop. The benefit is also that you can immediatly add the new character at the end of the new string instead of at the beginning (and then later start a new loop to swap from left to right), thus automatically swapping the string from left to right too.
improvement example:
js code:
var temp = Message.substring(6);
var str = "";
var charNew = "";
for(var i = 0; i < temp.length; i++){
// Assign the new character to the original character in case
// there is no replacement. Note: this also features a double
// purpose, see next comment.
charNew = temp.charAt(i);
for(var j = 0; j < alpha.length; j++){
// Also note that I replaced all the temp.charAt(i) with charNew
// eliminating all the (slow) string lookups.
if(charNew === alpha[j] || charNew === kappa[j]){
charNew = omega[j];
break;
}
if(charNew === omega[j]){
charNew = alpha[j];
break;
}
}
// instead of doing 'str+=charNew' and then making another loop to
// swap everything from left to right, we immediatly add the new
// character to the end of the new string
str = CharNew + str;
}
return str;
Also note the change from == (equality operator) to === (identity operator) which is faster.
See CookieRevised's reply to Script about lock messenger
----
PS: if you ever want to swap an entire string from left to right, instead of this:
js code:
var OriginalStr = "Hello World";
var NewStr = "";
for(var i = OriginalStr.length-1; i >= 0; i--){
NewStr+=temp.charAt(i);
}
return New Str
you can also do this:
js code:
var OriginalStr = "Hello World";
return OriginalStr.split('').reverse().join('')