Skip to content

Commit 542e90b

Browse files
committed
Added reduce
1 parent 22811f6 commit 542e90b

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

2013-02-03-assignment.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,8 +92,31 @@ The returned value of `condition(x)`, where `x` is a single element in the input
9292

9393
## Q4: Implement Reduce
9494

95+
`reduce` is a slightly tricker function than the previous two, because it requires keeping track of something in addition to having an optional **seed value**, also known as the initial value. The basic duty of `reduce` is to boil down a list of elements into a single element. Even though this sounds mundane, it can be used very creatively to implement much more complex functionality.
96+
97+
`reduce` takes a list `xs`, an iterating function `fn`, and an optional `seed`. The list `xs` will be an arbitrary list of elements. The iterating function `fn`, will be a function that takes in two parameters, the first of which being the accumulating `seed` value. The `seed` can be initially provided in the function call to `reduce`; however, if it is not specified, the first value of the list should be used as the seed. Each successive step in `reduce` will essentially replace what was originally the `seed`, with what is returned from the function `fn`. Hopefully, the examples below will clarify.
98+
99+
```javascript
100+
function reduce (xs, fn, seed) {
101+
// NOTE: that seed is optional; you should give the appropriate default in the function body
102+
// ...
103+
}
104+
```
105+
106+
Example Tests:
107+
108+
```javascript
109+
reduce([1, 2, 3, 4, 5, 6], function (memo, x) { return memo + x; }); // => 21
110+
reduce([1, 2, 3, 4, 5, 6], function (memo, x) { return memo + x; }, 21); // => 42
111+
reduce([1, 2, 3], function (memo, x) { return memo.concat([x * 2]); }, []); // => [2, 4, 6]
112+
```
113+
95114
### Hint
96115

116+
Choosing an appropirate default value for the `seed` may be tricky. The flow should be given seed -> first element -> undefined. So if an empty array is passed in, and no seed is provided, the result should be undefined.
117+
118+
A memoizer should be kept that is initialized to the value of the `seed`, and then passed along to the function `fn` along with each successive element. The value of this memoizer should be being set at each step.
119+
97120
---
98121

99122
## Q5: Prototypal Inheritance

assignments/q4-reduce.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
function reduce (xs, fn, seed) {
2+
// NOTE: that seed is optional; you should give the appropriate default in the function body
3+
// ...
4+
}

0 commit comments

Comments
 (0)