|
7 | 7 | const each = (elements, cb) => { |
8 | 8 | // Iterates over a list of elements, yielding each in turn to the `cb` function. |
9 | 9 | // This only needs to work with arrays. |
| 10 | + // You should also pass the index into `cb` as the second argument |
10 | 11 | // based off http://underscorejs.org/#each |
| 12 | + for (let i = 0; i < elements.length; i++) { |
| 13 | + cb(elements[i], i); |
| 14 | + } |
11 | 15 | }; |
12 | 16 |
|
13 | 17 | const map = (elements, cb) => { |
14 | 18 | // Produces a new array of values by mapping each value in list through a transformation function (iteratee). |
15 | 19 | // Return the new array. |
| 20 | + const mappedArr = []; |
| 21 | + each(elements, item => (mappedArr.push(cb(item)))); |
| 22 | + return mappedArr; |
16 | 23 | }; |
17 | 24 |
|
18 | 25 | const reduce = (elements, cb, memo = elements.shift()) => { |
19 | 26 | // Combine all elements into a single value going from left to right. |
20 | 27 | // Elements will be passed one by one into `cb`. |
21 | 28 | // `memo` is the starting value. If `memo` is undefined then make `elements[0]` the initial value. |
| 29 | + each(elements, (item) => { |
| 30 | + memo = cb(memo, item); |
| 31 | + }); |
| 32 | + return memo; |
22 | 33 | }; |
23 | 34 |
|
24 | 35 | const find = (elements, cb) => { |
25 | 36 | // Look through each value in `elements` and pass each element to `cb`. |
26 | 37 | // If `cb` returns `true` then return that element. |
27 | 38 | // Return `undefined` if no elements pass the truth test. |
| 39 | + for (let i = 0; i < elements.length; i++) { |
| 40 | + if (cb(elements[i])) return elements[i]; |
| 41 | + } |
| 42 | + return undefined; |
28 | 43 | }; |
29 | 44 |
|
30 | 45 | const filter = (elements, cb) => { |
31 | 46 | // Similar to `find` but you will return an array of all elements that passed the truth test |
32 | 47 | // Return an empty array if no elements pass the truth test |
| 48 | + const filteredValues = []; |
| 49 | + each(elements, (item) => { |
| 50 | + if (cb(item)) filteredValues.push(item); |
| 51 | + }); |
| 52 | + return filteredValues; |
33 | 53 | }; |
34 | 54 |
|
35 | 55 | /* Extra Credit */ |
36 | 56 | const flatten = (elements) => { |
37 | 57 | // Flattens a nested array (the nesting can be to any depth). |
38 | 58 | // Example: flatten([1, [2], [3, [[4]]]]); => [1, 2, 3, 4]; |
| 59 | + const flattenedArr = reduce(elements, (memo, item) => { |
| 60 | + if (Array.isArray(item)) return memo.concat(flatten(item)); |
| 61 | + return memo.concat(item); |
| 62 | + }, []); |
| 63 | + return flattenedArr; |
39 | 64 | }; |
40 | 65 |
|
41 | 66 | /* eslint-enable no-unused-vars, max-len */ |
|
0 commit comments