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
Write a function called
eachthat takes in an array and a callback function.eachshould iterate through all items in the array and call the callback function with each item and its index as parameters.eachshould return the original array that was passed in.Write a function called
mapthat takes in an array and a callback function.mapshould 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.Write a function called reduce that takes in an array of numbers.
reduceshould 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
eachandmap, 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.