bases.js icon indicating copy to clipboard operation
bases.js copied to clipboard

Simplify code

Open cimpok opened this issue 5 years ago • 0 comments

Thank you for this module. I'd like to share a small enhancement (simpler code, faster runnning) for the decoder part. instead of:

while (str.length) {
        c = str[str.length - 1];
        str = str.substr(0, str.length - 1);
        num += Math.pow(base, pos) * alphabet.indexOf(c);
        pos++;
    }

you could just write:

var ptr = str.length
while (0 < ptr--) {
    num += Math.pow(base, pos++) * alphabet.indexOf(str[ptr]);
}

There's no need repeatedly cutting and reallocating the string (a long operation) in the loop, keep the str intact, a simple pointer is much faster traversing it backwards. The '0<' in the while condition is to handle empty string as input.

cimpok avatar Feb 19 '20 12:02 cimpok