How to Implement Binary Search in JavaScript


function binarySearch (list, value) {
  // initial values for start, middle and end
  let start = 0
  let stop = list.length - 1
  let middle = Math.floor((start + stop) / 2)

  // While the middle is not what we're looking for and the list does not have a single item
  while (list[middle] !== value && start < stop) {
    if (value < list[middle]) {
      stop = middle - 1
    } else {
      start = middle + 1
    }

    // recalculate middle on every iteration
    middle = Math.floor((start + stop) / 2)
  }

  // if the current middle item is what we're looking for return it's index, else return -1
  return (list[middle] !== value) ? -1 : middle
}

const list = [2, 5, 8, 9, 13, 45, 67, 99]
console.log(binarySearch(list, 99)) // 7 -> returns the index of the item

How to Implement Merge Sort in JavaScript

How to Implement Merge Sort in JavaScript the easy way.


// Split the array into halves and merge them recursively 
function mergeSort (arr) {
  if (arr.length === 1) {
    // return once we hit an array with a single item
    return arr
  }

  const middle = Math.floor(arr.length / 2) // get the middle item of the array rounded down
  const left = arr.slice(0, middle) // items on the left side
  const right = arr.slice(middle) // items on the right side

  return merge(
    mergeSort(left),
    mergeSort(right)
  )
}

// compare the arrays item by item and return the concatenated result
function merge (left, right) {
  let result = []
  let indexLeft = 0
  let indexRight = 0

  while (indexLeft < left.length && indexRight < right.length) {
    if (left[indexLeft] < right[indexRight]) {
      result.push(left[indexLeft])
      indexLeft++
    } else {
      result.push(right[indexRight])
      indexRight++
    }
  }

  return result.concat(left.slice(indexLeft)).concat(right.slice(indexRight))
}

const list = [2, 5, 1, 3, 7, 2, 3, 8, 6, 3];
console.log(mergeSort(list)) // [ 1, 2, 2, 3, 3, 3, 5, 6, 7, 8 ];

Calculate time difference between two times in JS

function CountingMinutes(str) { 

  let arr = str.split("-");
  // console.log(arr[0]);
  // code goes here  
  let day = 24 * 60;
  
  let end = getMinutes(arr[1]);
  let start = getMinutes(arr[0]);
  
 // console.log('end is ' + end);
 // console.log('start is ' + start);
  if (end < start){
    end += day;
  }
  return (end-start) ; 
         
}

function getMinutes(time){
  
  let hr = parseInt(time.split(':')[0]);
  let min = parseInt(time.split(':')[1].match(/[0-9]/g).join(""));
  
  let morning = time.match(/am/g);
  let pm = time.match(/pm/g);
 // console.log(pm);
  if (pm && hr < 12){
    hr += 12;
  }
  else if (morning && hr === 12){ // convert midnight to zero
    hr += 12;
  }
  
  let totalMin = parseInt((hr*60) + min);
  
  return totalMin ;
}