1
\$\begingroup\$

I currently have this encoding function which simply subtracts one from each character code:

String.fromCharCode.apply(null, text.split("").map(function(v) {
    return v.charCodeAt() - 1;
}));

E.g. test becomes sdrs.

I know that this function is silly because it isn't a strong encoding algorithm, but that's not my point. The problem is that it is slow and causes a stack overflow for large strings (~130.000 in length).

I tried a regexp but that's even slower:

text.replace(/./g, function(v) {
    return String.fromCharCode(v.charCodeAt() - 1);
});

I tested both on jsPerf.

Currently, I'm executing a function for each character in both functions. How can I make a function that does the same thing as what these functions are doing, but executes faster without stack overflows?

\$\endgroup\$
5
\$\begingroup\$

Try looping through it with a simple for loop:

var b = '';
for (var i = 0; i < a.length; i++)
{
   b += String.fromCharCode(a.charCodeAt(i) - 1)
}
return b;
\$\endgroup\$
  • \$\begingroup\$ Wow, that seems amazingly fast. More than 20 times as fast in fact. Thanks! \$\endgroup\$ – pimvdb Aug 30 '11 at 15:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.