const solution = (array) => {
  function merge(leftA, rightA) {
    var results = [],
      leftIndex = 0,
      rightIndex = 0

    while (leftIndex < leftA.length && rightIndex < rightA.length) {
      if (leftA[leftIndex] < rightA[rightIndex]) {
        results.push(leftA[leftIndex++])
      } else {
        results.push(rightA[rightIndex++])
      }
    }
    var leftRemains = leftA.slice(leftIndex),
      rightRemains = rightA.slice(rightIndex)

    // add remaining to resultant array
    return results.concat(leftRemains).concat(rightRemains)
  }

  function mergeSort(array) {
    if (array.length < 2) {
      return array // Base case: array is now sorted since it's just 1 element
    }

    var midpoint = Math.floor(array.length / 2),
      leftArray = array.slice(0, midpoint),
      rightArray = array.slice(midpoint)

    return merge(mergeSort(leftArray), mergeSort(rightArray))
  }

  return mergeSort(array)
}

const solution = (array) => {
  function merge(leftA, rightA) {
    var results = [],
      leftIndex = 0,
      rightIndex = 0

    while (leftIndex < leftA.length && rightIndex < rightA.length) {
      if (leftA[leftIndex] < rightA[rightIndex]) {
        results.push(leftA[leftIndex++])
      } else {
        results.push(rightA[rightIndex++])
      }
    }
    var leftRemains = leftA.slice(leftIndex),
      rightRemains = rightA.slice(rightIndex)

    // add remaining to resultant array
    return results.concat(leftRemains).concat(rightRemains)
  }

  function mergeSort(array) {
    if (array.length < 2) {
      return array // Base case: array is now sorted since it's just 1 element
    }

    var midpoint = Math.floor(array.length / 2),
      leftArray = array.slice(0, midpoint),
      rightArray = array.slice(midpoint)

    return merge(mergeSort(leftArray), mergeSort(rightArray))
  }

  return mergeSort(array)
}

console.log(solution([11, 5, 6, 7, 2, 4, 6, -3, -2, 1])) // expected output [-3, -2, 1, 2, 4, 5, 6, 6, 7, 11]

console.log(solution([9, 6, 7, 4, 7, 2, 2, 4, 2, 3, 7, 7])) // expected output [2, 2, 2, 3, 4, 4, 6, 7, 7, 7, 7, 9]
