Sunday, May 22, 2016

'init' of undefined when using gapi with angular

This can be solved by calling gapi.auth2.init in window.gapi_onload and loading google api js through javascript, as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
export class AppComponent implements OnInit {
    ngOnInit() {
        const gappClientId = "xxxxxx.apps.googleusercontent.com";

        window.gapi_onload = function () {
            console.log("gapi onload called");
            var auth2 = gapi.auth2.init({
                client_id: gappClientId,
                scope: 'profile'
            });
        };
        var po = document.createElement('script');
        po.type = 'text/javascript';
        po.async = true;
        po.src = 'https://apis.google.com/js/auth2.js';

        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(po, s);

    }
}

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