My binary search algorithm implementation in JavaScript
Parsing command line arguments

I mentioned this in a previous review,
it seems I wasn't specific enough,
but this is an inefficient and unnatural way to parse command line arguments:


    process.argv.forEach(function (val, index, array) {
        var idx = 0, ar = undefined;

        try{

            // get the commandline argument for 
            // array values 
            if(index === 2){
                myArray = myArray.concat(val.split(",").map(function(num){
                    return parseInt(num);
                }));    
            }

            // third index is the number to be searched.
            if(index === 3){
                searchNum = parseInt(val)
            }

        }catch(e){
            console.log(e)
        }

    });



What's wrong with it?


For each index 0, 1, 2, 3, the loop compares the index against 2 and 3 repeatedly
If there are not enough arguments, the loop should not even begin
The command line parsing logic fails its purpose by not failing in case the arguments are invalid


The natural way to parse would be:


Check process.argv.length and fail if invalid
Check the type of each argument and fail if invalid


Consider this alternative, no looping, nice and simple:

function parseArgs(prog, argv) {
  if (argv.length != 2) {
    throw `usage: node ${prog} NUMS_CSV NUM`;
  }

  function validInt(s) {
    var num = parseInt(s, 10);
    if (isNaN(num)) {
      throw "Not a valid number: " + s;
    }
    return num;
  }

  return {
    nums: argv[0].split(',').map(validInt),
    target: validInt(argv[1])
  };
}

var args = parseArgs(process.argv[1], process.argv.slice(2));


Parsing integers

When using parseInt, it's recommended to specify the radix parameter, because although base 10 is a common default, it's not guaranteed across different implementations.
So to parse base 10 numbers, write parseInt(x, 10) instead of parseInt(x).

API design

The binary_search function searches for an element and returns two kinds of strings as result:


can't be found
Number N found at position X


This is very limiting.
It would be better to have binary_search return an index or -1 if not found,
and move the logic of formatting a string result into a dedicated function.