Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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 fast without stack overflows?

share|improve this question
add comment

migrated from stackoverflow.com Aug 30 '11 at 15:12

This question came from our site for professional and enthusiast programmers.

1 Answer

up vote 4 down vote accepted

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;
share|improve this answer
 
Wow, that seems amazingly fast. More than 20 times as fast in fact. Thanks! –  pimvdb Aug 30 '11 at 15:17
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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