I have written a code were I pass two sorted array of numbers from command line, and out is one array with numbers sorted.
the code is as follows,
(function(){
'use strict';
var getCommandLineVariables = getCommandLineVariables;
var mainFunction = mainFunction;
mainFunction();
function mainFunction(){
var array = getCommandLineVariables();
var firstArray = array[0],
secondArray = array[1],
mergedArray = [], i = 0, j = 0;
for(i = 0; i < firstArray.length; i++){
for(j = j; j < secondArray.length; j++){
if(firstArray[i] < secondArray[j]){ // if number from first array is less than number of second array
mergedArray.push(firstArray[i]);
break;
}else{ // if number of second array is less than number of first array
mergedArray.push(secondArray[j]);
}
} // end of for
/*
The below condition executes when
length of first array is greater than second array
*/
if(j >= secondArray.length){
mergedArray.push(firstArray[i]);
}
} // end of for
/*
If length of second array is greater than
first array
*/
for(j = j; j < secondArray.length;j++){
mergedArray.push(secondArray[j])
}
console.log(mergedArray);
} // mainFunction
/*
Capture the numbers passed as commandline arguments
*/
function getCommandLineVariables(){
var arg_array = process.argv.slice(2),
someArray = [];
if(arg_array.length !== 2){
throw "Pass two comma seperated numbers";
}
for(var i = 0; i < arg_array.length; i++){
someArray.push((function(someString){
var someArray = someString.split(",");
someArray = someArray.map(function(str){
return parseInt(str);
});
return someArray;
})(arg_array[i]));
} // end of for
return someArray;
} // end of getCommandLineVariables
})();
The output of the above code is as follows,
E:\DataStructuresAndAlgorithms\array>node mergeSortedArray01.js 1,3,100 2,4,5,7,10
[ 1, 2, 3, 4, 5, 7, 10, 100 ]
E:\DataStructuresAndAlgorithms\array>
One more output
E:\DataStructuresAndAlgorithms\array>node mergeSortedArray01.js 3,27,100 2,4,5,7,10
[ 2, 3, 4, 5, 7, 10, 27, 100 ]
E:\DataStructuresAndAlgorithms\array>
Can you please review my code a check is there any room for improvement, Can the above problem be solved in other ways.