Skip to content

Commit dd317f3

Browse files
SunJieMingSunJieMing
authored andcommitted
Added array solutions
1 parent cfc8f2b commit dd317f3

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

src/arrays.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,35 +7,60 @@
77
const each = (elements, cb) => {
88
// Iterates over a list of elements, yielding each in turn to the `cb` function.
99
// This only needs to work with arrays.
10+
// You should also pass the index into `cb` as the second argument
1011
// based off http://underscorejs.org/#each
12+
for (let i = 0; i < elements.length; i++) {
13+
cb(elements[i], i);
14+
}
1115
};
1216

1317
const map = (elements, cb) => {
1418
// Produces a new array of values by mapping each value in list through a transformation function (iteratee).
1519
// Return the new array.
20+
const mappedArr = [];
21+
each(elements, item => (mappedArr.push(cb(item))));
22+
return mappedArr;
1623
};
1724

1825
const reduce = (elements, cb, memo = elements.shift()) => {
1926
// Combine all elements into a single value going from left to right.
2027
// Elements will be passed one by one into `cb`.
2128
// `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;
2233
};
2334

2435
const find = (elements, cb) => {
2536
// Look through each value in `elements` and pass each element to `cb`.
2637
// If `cb` returns `true` then return that element.
2738
// 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;
2843
};
2944

3045
const filter = (elements, cb) => {
3146
// Similar to `find` but you will return an array of all elements that passed the truth test
3247
// 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;
3353
};
3454

3555
/* Extra Credit */
3656
const flatten = (elements) => {
3757
// Flattens a nested array (the nesting can be to any depth).
3858
// 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;
3964
};
4065

4166
/* eslint-enable no-unused-vars, max-len */

0 commit comments

Comments
 (0)