@@ -9,29 +9,56 @@ 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 newArr = [ ] ;
21+ for ( let i = 0 ; i < elements . length ; i ++ ) {
22+ newArr [ i ] = cb ( elements [ i ] ) ;
23+ }
24+ return newArr ;
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 i = 0 ;
33+ if ( startingValue === undefined ) {
34+ startingValue = elements [ 0 ] ;
35+ i = 1 ;
36+ }
37+ let combined = startingValue ;
38+ for ( ; i < elements . length ; i ++ ) {
39+ combined = cb ( combined , elements [ i ] ) ;
40+ }
41+ return combined ;
2442} ;
2543
2644const find = ( elements , cb ) => {
2745 // Look through each value in `elements` and pass each element to `cb`.
2846 // If `cb` returns `true` then return that element.
2947 // Return `undefined` if no elements pass the truth test.
48+ for ( let i = 0 ; i < elements . length ; i ++ ) {
49+ if ( cb ( elements [ i ] ) ) return elements [ i ] ;
50+ }
51+ return undefined ;
3052} ;
3153
3254const filter = ( elements , cb ) => {
3355 // Similar to `find` but you will return an array of all elements that passed the truth test
3456 // Return an empty array if no elements pass the truth test
57+ const newArr = [ ] ;
58+ for ( let i = 0 ; i < elements . length ; i ++ ) {
59+ if ( cb ( elements [ i ] ) ) newArr . push ( elements [ i ] ) ;
60+ }
61+ return newArr ;
3562} ;
3663
3764/* STRETCH PROBLEM */
0 commit comments