Interview Question for JavaScript

Rules

  • If input is “1-4”, output should be “1,2,3,4”.
  • If input is “1-4,6”, output should be “1,2,3,4,6”
  • Sort the Output in Asending order and no repeated number
  • Validate the input

HTML

<input type="text" id="userVal" placeholder="Enter value">
<button id="userSubmit" onclick="userOutputFun()">Submit</button>
<div id="userOutput"></div>

Javascript

function userOutputFun(){
	var userVal = document.getElementById("userVal").value;
  var allNum = getAllNumbers(userVal);
  if( !isValid(allNum) ){
  	document.getElementById("userOutput").innerHTML = "InValid Input";
  	return false;
  }
  var findUniqueNum = findUnique(allNum);
  var sortedVal = findUniqueNum.sort(function(a, b){return a-b});
  document.getElementById("userOutput").innerHTML = sortedVal.join(",");
}
function getAllNumbers(userVal){
	var arr1 = userVal.split(",");
  var arr2 = [];
  for(var i = 0; i < arr1.length; i++){
  	var arr3 = arr1[i].split("-");
  	if(arr3.length == 1){
    	arr2.push(arr3[0]);
    }
    else{
    	for(var j = parseInt(arr3[0]); j < parseInt(arr3[1])+1; j++){
      	arr2.push(j);
      }
    }
  }
  return arr2;
}

function findUnique(allNum){
	var arr = [];
  recursiveFun(allNum);
  function recursiveFun(allNum){
  	arr = [];
    for(var i = 0; i < allNum.length; i++){
      for(var j = 0; j < allNum.length; j++){
				if( allNum[i] == allNum[j] && i !== j ){
        	allNum.splice(j, 1);
          return recursiveFun(allNum);
        }
      }  
      arr.push(allNum[i]);
    }
  }
  return arr;
}

function isValid(userVal){
	for( var i = 0; i < userVal.length; i++ ){
  	if( !parseInt(userVal[i]) ){
    	return false;
    }
  }
  return true
}


DEMO HERE

Published by

Shiyam

My passion became my profession , I'm a driven, energetic and proactive tech professionally. I consider myself an engagement professional, as I don't simply provide solutions, I create them. I am a continuous learner – always looking for new technologies, in my spare time I search Google for the latest trends . I like to think of myself as a futurist and I'm a Full Stack JavaScript Developer.

Leave a comment