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?

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Aug 30, 2011 at 15:03
\$\endgroup\$
0

1 Answer 1

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;
answered Aug 30, 2011 at 15:15
\$\endgroup\$
1
  • \$\begingroup\$ Wow, that seems amazingly fast. More than 20 times as fast in fact. Thanks! \$\endgroup\$ Commented Aug 30, 2011 at 15:17

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.