One of my favourite JavaScript interview questions

#javascript

There is an api addRemote we can call to perform addition to the sum of two numbers on a remote server. It takes 100ms to get back the result.

const addRemote = async (a, b) =>
  new Promise((resolve) => {
    setTimeout(() => resolve(a + b), 100)
})

Write a function that takes any number of numbers and use this api to return a promise that resolves to the total sum.

add(1).then(console.log) // log out 1
add(1,2).then(console.log) // log out 3
add(1,2,3).then(console.log) // log out 6

Basic solution#

function add(...inputs) {
  return inputs.reduce(
    (sumPromise, num) => sumPromise.then((sum) => addRemote(sum, num)),
    Promise.resolve(0)
  )
}

A divide and conquer approach#

function add(...inputs) {
  const promises = []
  while (inputs.length) {
    const [a = 0, b = 0] = inputs.splice(0, 2)
    promises.push(addRemote(a, b))
  }

  return Promise.all(promises).then((sums) =>
    sums.length === 1 ? sums[0] : add(...sums)
  )
}

After they arrive at this improved solution, ask them to improve the performance again. They should be aware of using caching/memoization to optimize away repetitive calculations and be able to talk about trade-offs that come with caching. e.g. memory usage, cache busting, and other challenges such as how we can avoid calling the api if the input list consists of the. same numbers with a different order