Tuesday, February 21, 2017

JSSeries : Javascript + conversion during comparison

Here is an example of using the compare function using the plus operator to convert the value to a number. It turns out 2 and Two are equal when Two isNan converted with the + in front of the value :) Javascript never ceased to impress LOL.


Code:

function compare(v1, v2, change) {
    // The + converts to a number if possible

    var itm1 = v1;
    var itm2 = v2;

    if (change) {
        itm1 = +v1;
        itm2 = +v2;
    }

    console.log("itm1:"+itm1+" itm2:"+itm2);

    if (itm1 < itm2) { return -1; }
    if (itm2 < itm1) { return 1; }

    return 0;
}

one = "2";
two = "Two";
console.log("Test with +");
console.log("------");
console.log(compare(one, two, true));
console.log("");
console.log("Test without +");
console.log("------");
console.log(compare(one, two, false));



Output:

Test with +
------
itm1:2 itm2:NaN
0

Test without +
------
itm1:2 itm2:Two
-1

Saturday, February 4, 2017

My Ugly JS Xmas Tree

/**
 * My Ugly JS Christmas Tree
 */

var t = 1;
var s = 22;
for (var i = 1 ; i <= 20 ; i++) {

var spaces = "";
for (var z = 0 ; z < s ; z++) {
spaces = spaces + " ";
}

s = s - 1;
t = t + (i * t);
console.log(spaces + t + t);
}

for (var i = 0 ; i < 3 ; i++) {
console.log("                xxxxxxxxxx");
}