@@ -8,33 +8,67 @@ 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.
1010 // based off http://underscorejs.org/#each
11+ for ( let i = 0 ; i < elements . length ; i ++ ) {
12+ cb ( elements [ i ] , i ) ;
13+ }
1114} ;
1215
1316const map = ( elements , cb ) => {
17+ const myArr = [ ] ;
18+ each ( elements , ( el , i ) => {
19+ myArr . push ( cb ( el , i ) ) ;
20+ } ) ;
21+ return myArr ;
1422 // Produces a new array of values by mapping each value in list through a transformation function (iteratee).
1523 // Return the new array.
1624} ;
1725
18- const reduce = ( elements , cb , memo ) => {
26+ const reduce = ( elements , cb , memo = elements . shift ( ) ) => {
1927 // Combine all elements into a single value going from left to right.
2028 // Elements will be passed one by one into `cb`.
2129 // `memo` is the starting value. If `memo` is undefined then make `elements[0]` the initial value.
30+ each ( elements , ( item ) => {
31+ memo = cb ( memo , item ) ;
32+ } ) ;
33+ return memo ;
2234} ;
2335
2436const find = ( elements , cb ) => {
2537 // Look through each value in `elements` and pass each element to `cb`.
2638 // If `cb` returns `true` then return that element.
2739 // Return `undefined` if no elements pass the truth test.
40+ let flag ;
41+ elements . forEach ( ( element ) => {
42+ if ( cb ( element ) ) flag = element ;
43+ } ) ;
44+ return flag ;
2845} ;
2946
3047const filter = ( elements , cb ) => {
3148 // Similar to `find` but you will return an array of all elements that passed the truth test
3249 // Return an empty array if no elements pass the truth test
50+ const returnArr = [ ] ;
51+ elements . forEach ( ( element ) => {
52+ if ( cb ( element ) ) returnArr . push ( element ) ;
53+ } ) ;
54+ return returnArr ;
3355} ;
3456
3557const flatten = ( elements ) => {
3658 // Flattens a nested array (the nesting can be to any depth).
3759 // Example: flatten([1, [2], [3, [[4]]]]); => [1, 2, 3, 4];
60+ const newArr = [ ] ;
61+ elements . forEach ( ( element ) => {
62+ if ( Array . isArray ( element ) ) {
63+ const nest = flatten ( element ) ;
64+ nest . forEach ( ( nestedEl ) => {
65+ newArr . push ( nestedEl ) ;
66+ } ) ;
67+ } else {
68+ newArr . push ( element ) ;
69+ }
70+ } ) ;
71+ return newArr ;
3872} ;
3973
4074/* eslint-enable no-unused-vars, max-len */
0 commit comments