Broadly Applicable

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");
}



Saturday, June 4, 2016

JS Series: Node.js vs. Java Simple Speed Test

This evening after working through a few asynchronous and synchronous methods in node.js to process huge files I thought I would write the same simple math routine in JavaScript/node.js and again in Java. I have been impressed so far with the performance of node and my JS code. The fact that I am getting the speed I do and I get it with a save then run without compile has me convinced JS is a contender for my next time sensitive project.



--------------------------
Node/JavaScript 
--------------------------

var start = new Date();
var n = 1;
for (var i = 1 ; i <= 100000000 ; i++) {
    n = n + i;
}
var end = new Date();
var tm = end.getTime() - start.getTime();
console.log('tm->'+tm+'milliseconds');
console.log('n->'+n);



--------------------------
Java
--------------------------

import java.util.Date;
class Summer {
    public static void main(String[] args) {
        Date startDate = new Date();
        long n = 1;
        for (long i = 1 ; i <= 100000000 ; i++) {
            n = n + i;
        }
        Date endDate = new Date();
        long tm = endDate.getTime() - startDate.getTime();
        System.out.println("tm->" + tm + "milliseconds");
        System.out.println("n->"+n);
    }
}


Results

Minus the boilerplate class stuff in Java each of these are exactly 8 lines of code. So how did they do?

Davids-MacBook-Air:numbers dbell$ java Summer
tm->41milliseconds
n->5000000050000001
Davids-MacBook-Air:numbers dbell$ node summer.js
tm->139milliseconds

n->5000000050000001


The difference isn't drastic for such a simple example but Java runs in 1/3 the time and is our winner!

Enjoy!



Friday, June 3, 2016

JS Series: iTunes Connect Test Flight External Users Notify CSV Generator Using Node.js

In this post I want to share a script that I wrote to parse through the iTunes Connect Test Flight external user test to determine which users have been notified of my new app build but who have not installed. The goal is to gather up the list of those users and re-create a new comma separated file for upload. This will cause all those users to be re-notified and will hopefully lead to more downloads of test builds.

Note: This script requires you install node.js to work.


Step 1: Get users into a users.txt file.
Log into iTunes connect,  click on my apps, click on your app name, visit the test flight section, click on external testers. Highlight and copy/paste the list of users into a new text file called users.txt and place into a directory. The file should look similar to this screenshot below.


Step 2: In the same directory as this users.txt file copy and paste the following javascript file.

var fs = require('fs');
var lineReader = require('readline').createInterface({
    input: require('fs').createReadStream('users.txt')
});

var date = new Date();
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();

var csvFile = 'notify_' + monthIndex + day + year + '.csv';
console.log('csvFile:' + csvFile);

fs.closeSync(fs.openSync(csvFile, 'w'));

var cnt = 0;
var fName = '';
var lName = '';
var email = '';
var notified = false;

lineReader.on('line', function (line) {
    if (line != '') {
        line = line.replace(',', '');
        switch (cnt) {
        case 0:
            email = line;
            break;
        case 1:
            var names = line.split(' ');
            fName = names[0];
            lName = names[1];
            break;
        case 2:
            if (line === 'Notified') {
                notified = true;
            }
            break;
        default:
        }
        cnt = cnt + 1;
    } else {
        if (notified) {
            var lne = fName + ',' + lName + ',' + email + '\n';
            fs.appendFile(csvFile, lne, function (err) {
                if (err !== null) {
                    console.log('err:' + err);
                }
            });
        }
        cnt = 0;
        fName = '';
        lName = '';
        email = '';
        notified = false;
    }
});

Step 3: Run Script
Open up a terminal and go into the directory where the user.txt and the above script are found. (I called mine ReadFile.js).

Davids-MacBook-Air:itunes dbell$ node ReadFile.js 
csvFile:notify_532016.csv

When you run the file it should produce a new notify csv file. View the file (I used cat) and you should see only those users listed who need to be notified again. 


Davids-MacBook-Air:itunes dbell$ cat notify_532016.csv 

Bob,Smith,bobsmith@outlook.com




Step 4: iTunes CSV Load
Go back into iTunes connect now where you copied out your users. Edit and remove each user manually who had only notified next to their name. You can use this new notify csv as a reference for who to remove. Then after they are removed use the add functionality to upload a csv file. Select  your new csv file and then click on save.



In my next Javascript post I will use the same users.txt file to determine how many users have installed and what build and how many are only notified as a means to provide a statistic for your app.

Enjoy!

Thursday, May 26, 2016

JS Series: Function vs. Object Encapsulation

While going through JS and trying to figure out how functions work vs. objects since you know, functions are objects, I decided to put together a short example of how encapsulation works in JavaScript. Basically you can create private and public fields and methods but not inside an object you have to use a function.

I'm well aware there are many more cases where this basic principle gets confusing or misused. An example where this all falls apart is changing out the var keyword on the cnt property inside the CalculatorFunction.js file. However this is meant to be a very simple example of how you can hide fields inside a file. You can do the same thing for methods by not doing a this.func = function() and instead just declaring the function() you wish to use privately.

Explanation
The concept behind this test was to create the same thing as an object and a function. Call the method to add two values together. In this add function it should increase the cnt of methods executed and store that value. After calling that method the program tries to modify the cnt field in both types to see the result. In the function the cnt is protected and in the object it is not.


Screenshot of my results



Index.html

<html>

<body>
    <h1>Scoping Tests</h1>
    <script src="CalculatorObject.js"></script>
    <script src="CalculatorFunction.js"></script>

    <script>
        var a = 5;
        var b = 25;
        var c = 30;

        var cf = new CalculatorFunction();

        var rslt1 = calculatorObject.add(a, b);
        rslt1 = rslt1 + calculatorObject.add(b, c);
        var rslt2 = cf.add(a, c);

        document.write("Result1->" + rslt1 + " count->" + calculatorObject.getCnt());
        document.write("<br/>Result2->" + rslt2 + " count->" + cf.getCnt());
        
        
        /* Testing function encapsulation using var */
        document.write("<br/><br/><b>Test Function Encapsulation</b><br/>");
        cf.cnt = 25;
        document.write("<br/>Setting cf.cnt = 25 won't matter. getCnt() is still: " + cf.getCnt() + " aka encapsulation in JS.");
        
        
        /* Testing object encapsulation using object parameters */
        document.write("<br/><br/><b>Test Object Encapsulation</b><br/>");
        calculatorObject.cnt = 999;
        document.write("<br/>Setting calculatorObject.cnt = 999. getCnt() on object should return 999: " + calculatorObject.getCnt() + " aka non-encapsulation.");
        
    </script>
</body>

</html>


CalculatorObject.js

var calculatorObject = {
    "cnt": 0,
   
    "add": function (a, b) {
        'use strict';
        this.cnt = this.cnt + 1;
        return a + b;
    },
   
    "subtract": function (a, b) {
        'use strict';
        this.cnt = this.cnt + 1;
        return a - b;
    },
   
    "getCnt": function () {
        'use strict';
        return this.cnt;
    }
};


CalculatorFunction.js

function CalculatorFunction() {
   
    'use strict';
    var cnt = 0;
    console.log(cnt);
    this.add = function (a, b) {
        cnt = cnt + 1;
        return a + b;
    };

    this.subtract = function (a, b) {
        cnt = cnt + 1;
        return a - b;
    };

    this.getCnt = function () {
        return cnt;
    };

}


Though this is a very small and simple example it will help you to understand just how these two items work in relation to what problem you are trying to solve in your source code.

Enjoy!

JS Series: JavaScript xmlHttp GET Request


In this post I will provide a code sample for how to do simple xmlHttp GET requests and update a unordered list of times to display great nerdy Chuck Norris quotes using the icndb (Internet Chuck Norris Database).

In order to keep things simple at the beginning I'm going to try write all my JavaScript in the same html file. Once we move to modules and server side I'm sure that won't be possible but for now let's keep things simple. 


1. Create a new file called index.html and paste the following code into the file and save.

<script>
    function httpGetAsync() {  
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() { 
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            callback(xmlHttp.responseText);
        }
    }
    xmlHttp.open("GET", "http://api.icndb.com/jokes/random", true); // true for asynchronous 
    xmlHttp.send(null);
}

function callback(respString) {
            var joke = getJoke(respString);
            var quoteList = document.getElementById("quoteList");
            var li = document.createElement("li");
            li.appendChild(document.createTextNode(joke));
            quoteList.appendChild(li);
}

function getJoke(respString) {
    var obj = JSON.parse(respString);
    return obj.value.joke;
}

</script>
<input type="button" value="Get Quote" onclick="httpGetAsync()" />
<ul id="quoteList"></ul>

2. Open The File With Your Browser

Locate the new index.html file you just created and double click on it. This should open the file along with the script code into your browser. You should be supplied with a single button with a label called "Get Quote". Clicking on this button will fire off an asynchronous get request to the incdb server and return a string of data (JSON format) which we will show in the browser.




ScreenShot



Items To Note

  • There was a button added to the page which called the httpGetAsync() JS function.
  • The httpGetAsync method created a new xmlHttp object and opened a GET connection to a specific URL and called send.
  • The xmlHttp object created has a callback function assigned when the state of the connection changed.
  • This change fired off a call to a new method aptly named callback which took the response json returned. 
  • The response json (JavaScript Object Notation) was then created using the JSON.parse method which takes a regular string and creates the actual JSON object.
  • This method also accesses the joke object value and returns it to the calling function.
  • Next the callback finds the UL tag by id, creates a new LI element, appends the joke text into that LI tag, then appends that LI back into the UL tag so the list continues to grow each time you hit the Get Quote button.

I hope you enjoyed this simple yet powerful example of how to do a GET with JavaScript. As I continue down this path I look forward to the many challenges I will face. I can already tell just how powerful this whole JS thing is nowadays with this simple script. 

Enjoy!


JavaScript oh JavaScript

The World is eati.. wait.. no JavaScript is eating the world. That is the headline I keep reading everywhere I look. I have been coding JavaScript since the nineties. I have never really given JS any respect mainly because it was always just a toy language or something to add a little functionality to a web page. Well times sure have changed and it seems like everywhere I look you can use JS to do about anything from IOT to server side programmer and beyond.

For this reason I have decided to embark on a new journey to the land of current JS. I'll try to post new articles as I teach myself all the new features in say ES6 to how to do try module encapsulation (looking forward to that one) and also our best friend Node.js which along with npm is one heck of a tool. So buckle in as we take a very seasoned veteran Java programmer and build out tools and products using nothing but JavaScript.