Sunday, May 1, 2016

In place swap in Javascript

You can do a in-place swap using a buffer in JS with the following code. Strings are themselves immutable in JS. Hence, you cannot do a in-place swap with Strings in JS.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
function reverseString(str) {
    var temp;
    for (var i = 0; i<str.length/2; i++) {
        temp = str[i];
        str[i] = str[str.length - i - 1];
        str[str.length - i - 1] = temp;
    }
}

var a = new Buffer("how are you");
console.log(a.toString());
reverseString(a);
The above code outputs:

1
2
how are you
uoy era woh

No comments:

Post a Comment