Interview Prep - Iterators

Today you'll be implementing iterator functions on the whiteboard in groups of three. Since there are three problems, each group member should take a turn "driving" for one problem with the other two as support ("navigators").

Note: DO NOT use any built-in iterator functions from Underscore or another library. You will often be asked in interviews to implement well-known methods like this from scratch as problem-solving exercises.

Problems

  1. Write a function called each that takes in an array and a callback function. each should iterate through all items in the array and call the callback function with each item and its index as parameters. each should return the original array that was passed in.

  2. Write a function called map that takes in an array and a callback function. map should iterate through all items in the array, call the callback function with each item and its index as parameters, and return a new array of the results.

  3. Write a function called reduce that takes in an array of numbers. reduce should return the sum of all the numbers in the array.

How to Get Started

  • Use pseudo-code to diagram the input and output of your function before writing any code on the board.
  • Come up with at least three examples of test input, and write down the expected output. Hint: For each and map, one of your test inputs will be a function.
  • Only when you have pseudo-code and test input with expected output should you write code to implement the body of the function.