ES6+medium

Implement Array.prototype.reduce from scratch

Implement `Array.prototype.myReduce` that behaves identically to the native `reduce`. Handle both the case where an initial value is provided and when it is not.

Asked at Apple, Meta

#arrays#prototype#accumulator

Answer

Array.prototype.myReduce = function(callback, initialValue) {
  if (typeof callback !== 'function') {
    throw new TypeError(callback + ' is not a function')
  }

  const arr = this
  let accumulator
  let startIndex

  if (arguments.length >= 2) {
    accumulator = initialValue
    startIndex = 0
  } else {
    if (arr.length === 0) {
      throw new TypeError('Reduce of empty array with no initial value')
    }
    accumulator = arr[0]
    startIndex = 1
  }

  for (let i = startIndex; i < arr.length; i++) {
    if (Object.prototype.hasOwnProperty.call(arr, i)) {
      accumulator = callback(accumulator, arr[i], i, arr)
    }
  }

  return accumulator
}

// Tests
;[1, 2, 3, 4].myReduce((acc, x) => acc + x, 0)  // 10
;[1, 2, 3, 4].myReduce((acc, x) => acc + x)      // 10
;['a','b','c'].myReduce((acc, x) => acc + x)      // "abc"

Source: frontendinterviewhandbook.com — Apple

Practise more ES6+ questions →