@@ -9,29 +9,63 @@ const each = (elements, cb) => {
99 // This only needs to work with arrays.
1010 // You should also pass the index into `cb` as the second argument
1111 // based off http://underscorejs.org/#each
12+ for (let i = 0; i < elements.length; i++) {
13+ cb(elements[i], i);
14+ }
1215};
1316
1417const map = (elements, cb) => {
1518 // Produces a new array of values by mapping each value in list through a transformation function (iteratee).
1619 // Return the new array.
20+ const newArray = [];
21+ for (let i = 0; i < elements.length; i++) {
22+ newArray.push(cb(elements[i]));
23+ }
24+ return newArray;
1725};
1826
1927const reduce = (elements, cb, startingValue) => {
2028 // Combine all elements into a single value going from left to right.
2129 // Elements will be passed one by one into `cb` along with the `startingValue`.
2230 // `startingValue` should be the first argument passed to `cb` and the array element should be the second argument.
2331 // `startingValue` is the starting value. If `startingValue` is undefined then make `elements[0]` the initial value.
32+ let value;
33+ if (startingValue === undefined) {
34+ value = elements[0];
35+ for (let i = 1; i < elements.length; i++) {
36+ value = cb(value, elements[i]);
37+ }
38+ } else {
39+ value = startingValue;
40+ for (let i = 0; i < elements.length; i++) {
41+ value = cb(value, elements[i]);
42+ }
43+ }
44+ return value;
2445};
2546
2647const find = (elements, cb) => {
2748 // Look through each value in `elements` and pass each element to `cb`.
2849 // If `cb` returns `true` then return that element.
2950 // Return `undefined` if no elements pass the truth test.
51+ for (let i = 0; i < elements.length; i++) {
52+ if (cb(elements[i]) === true) {
53+ return elements[i];
54+ }
55+ }
56+ return undefined;
3057};
3158
3259const filter = (elements, cb) => {
3360 // Similar to `find` but you will return an array of all elements that passed the truth test
3461 // Return an empty array if no elements pass the truth test
62+ const truth = [];
63+ for (let i = 0; i < elements.length; i++) {
64+ if (cb(elements[i]) === true) {
65+ truth.push(elements[i]);
66+ }
67+ }
68+ return truth;
3569};
3670
3771/* STRETCH PROBLEM */
0 commit comments