- Identify the parts of the Accumulator Pattern
- Use the Accumulator Pattern to solve common problems
Here is an example of the Accumulator Pattern in action:
function joinWords (words) {
let result = ""
for (var i = 0; i < words.length; i++) {
result += words[i]
}
return result;
}
if var words = ['delicious', 'lobster', 'bisque']
then joinWords(words) -> "deliciouslobsterbisque"
further explanation here: https://learn.galvanize.com/content/gSchool/javascript-curriculum/master/20_Functional_Patterns/04_Accumulator_Pattern/README.md
- Define the functions
- Declare and return the result variable
- Set up the iteration
- Alter the accumulator as necessary
Turn to your neighbor and discuss what the Accumulator Pattern is in your own words. Try to come up with a real-world example of the "Accumulator Pattern".
Take a minute to identify the input and output in the joinWords
example above. What are their data types?
When finished, identify the input and output of the findMax
function:
function findMax(nums) {
}
Looking at the findMax
function, identify the type and value of the result
.
When finished, identify the result type and value for a joinWords
function.
How about an allEven
function?
allEven([2, 4, 6]) // returns true
Looking at the findMax
function, what iteration style would you choose?
How about this function:
flipFlop({ name: 'Sandy', hair: 'blue' }) // returns { Sandy: 'name', blue: 'hair' }
Looking at the findMax
function, how would you alter the accumulator (result
variable) inside the loop?
How about this function:
doubleNumbers([1, 3]) // returns [2, 6]
Try implementing the following functions using the accumulator pattern:
countLetters(word)
sum(nums)
addTo(nums, value)
addTo([1, 2, 3], 3) -> [4, 5, 6]
addTo([], 3) -> []
diff(array1, array2)
diff([1, 2, 3], [2, 3, 4]) -> [1, 1, 1]
diff([1, 2, 3], [2, 2, 2]) -> [1, 0, -1]
diff([1, 2, 3], [1, 2, -1]) -> [0, 0, -4]
Given this input:
var medals = [
{country: 'South Korea', type: 'gold'},
{country: 'Russia', type: 'silver'},
{country: 'Norway', type: 'gold'},
{country: 'Norway', type: 'silver'},
{country: 'Sweden', type: 'bronze'},
{country: 'United States', type: 'gold'},
]
Write a goldCountries
function that returns a list of all countries that won gold medals.
goldCountries(medals) -> ['South Korea', 'Norway', 'United States']