JavaScript String Incrementer

4    28 Jan 2017 20:56 by u/xobodox

I needed this for something.. but, it could be used for a brute force attack on a hash, etc.. I don't like that a String object cannot be edited in place; but this runs with decent performance through NodeJS..

String.prototype.increment = function (min, max) {
    var arr = Array.from(this);
    var last = arr.length - 1;
    if (last < 0) {
        arr[0] = String.fromCharCode(min);
        return arr.join('');
    }
    var charCode = arr[last].charCodeAt(0);
    while(charCode >= max) {
        arr[last--] = String.fromCharCode(min);
        if (last < 0) break;
        var charCode = arr[last].charCodeAt(0);
    }
    if (last < 0) {
        arr[arr.length] = String.fromCharCode(min);
    } else {
        arr[last] = String.fromCharCode(arr[last].charCodeAt(0)+1);
    }
    return arr.join('');
}
// example usage
var x = "";
while(x.length < 2) {
    //x = x.increment(32, 55); //32 is ASCII <space>, 55 is ASCII 7
    //x = x.increment(48, 57); //48 is ASCII 0, 57 is ASCII 9
    x = x.increment(65, 90); //65 is ASCII A, 90 is ASCII Z
    console.log("x=[",x,"]");
}

1 comment

0

Looks like this could be used to check for memory leaks in NodeJS.. LOL!

<--- Last few GCs --->
  404429 ms: Scavenge 1398.5 (1457.3) -> 1398.5 (1457.3) MB, 1.4 / 0 ms (+ 3.0 ms in 1 steps since last GC) [allocation failure] [incremental marking delaying mark-sweep].
  405718 ms: Mark-sweep 1398.5 (1457.3) -> 1398.5 (1457.3) MB, 1289.0 / 0 ms (+ 4.0 ms in 2 steps since start of marking, biggest step 3.0 ms) [last resort gc].
  407048 ms: Mark-sweep 1398.5 (1457.3) -> 1398.5 (1457.3) MB, 1329.2 / 0 ms [last resort gc].
<--- JS stacktrace --->
==== JS stack trace =========================================
Security context: 000000F4D00B4639 <JS Object>
    1: nextTick [node.js:~478] [pc=000003EF61D88171] (this=0000016262607271 <a process with map 0000026F3EB10D31>,callback=00000356E8BE2381 <JS Function afterWrite (SharedFunctionInfo 00000356E8B2B521)>)
    2: arguments adaptor frame: 5->1
    3: onwrite(aka onwrite) [_stream_writable.js:~322] [pc=000003EF61D759FC] (this=000000F4D00041B9 <undefined>,stream=00000356E8BE0169 <a WriteStream wit...
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

Also, if you want to check performance between NodeJS and C..

#include <stdio.h>
#include <string.h>
void chars_increment(char* arr, char min, char max)
{
    ssize_t last = strlen(arr)-1;
    if (last < 0) {
        arr[0] = min;
        return;
    }
    while(arr[last] >= max) {
        arr[last--] = min;
        if (last < 0) break;
    }
    if (last < 0) {
        arr[strlen(arr)] = min; //potentially unsafe
    } else {
        arr[last]++;
    }
}
int main(int argc, char* argv[])
{
    char buf[80];
    memset(buf, 0x0, sizeof(buf));
    while (strlen(buf) < 6) {
        chars_increment(buf, 65, 90);
        printf("buf = [%s]\n", buf);
    }
    return 0;
}