1- // Complete the following functions.
2- // These functions only need to work with arrays.
3- // Do NOT use the built in array methods to solve these. forEach, map, reduce, filter, includes, etc.
4- // You CAN use concat, push, pop, etc. but do not use the exact method that you are replicating
5- // You can use the functions that you have already written to help solve the other problems
6-
71const each = ( elements , cb ) => {
82 for ( let i = 0 ; i < elements . length ; i ++ ) {
93 cb ( elements [ i ] , i ) ;
@@ -19,21 +13,18 @@ const map = (elements, cb) => {
1913} ;
2014
2115const reduce = ( elements , cb , startingValue ) => {
22- const newElements = elements . slice ( ) ; // creating a new array
23- if ( ! startingValue ) { // if its not pointing on the 1st element
24- startingValue = newElements . shift ( ) ; // shift return the 1st el
16+ const newElements = elements . slice ( ) ;
17+ if ( ! startingValue ) {
18+ startingValue = newElements . shift ( ) ;
2519 }
26- let memo = startingValue ; // this is memoazation for the staringValue
27- each ( newElements , ( el ) => { // run a forEach on el and a callback where memo refrence the cb
20+ let memo = startingValue ;
21+ each ( newElements , ( el ) => {
2822 memo = cb ( memo , el ) ;
2923 } ) ;
3024 return memo ;
3125} ;
3226
3327const find = ( elements , cb ) => {
34- // Look through each value in `elements` and pass each element to `cb`.
35- // If `cb` returns `true` then return that element.
36- // Return `undefined` if no elements pass the truth test.
3728 for ( let i = 0 ; i < elements . length ; i ++ ) {
3829 if ( cb ( elements [ i ] ) ) {
3930 return elements [ i ] ;
@@ -42,8 +33,6 @@ const find = (elements, cb) => {
4233} ;
4334
4435const filter = ( elements , cb ) => {
45- // Similar to `find` but you will return an array of all elements that passed the truth test
46- // Return an empty array if no elements pass the truth test
4736 const newArr = [ ] ;
4837 for ( let i = 0 ; i < elements . length ; i ++ ) {
4938 if ( cb ( elements [ i ] ) ) {
@@ -56,10 +45,6 @@ const filter = (elements, cb) => {
5645/* STRETCH PROBLEM */
5746
5847const flatten = ( elements ) => {
59- // Flattens a nested array (the nesting can be to any depth).
60- // Example: flatten([1, [2], [3, [[4]]]]); => [1, 2, 3, 4];
61- // const reducedArr = elements.reduce((a, n) => a.concat(n), []);
62- // return reducedArr;
6348 const newArr = [ ] ;
6449 Object . values ( elements ) . forEach ( ( e ) => {
6550 if ( typeof e === 'number' ) {
0 commit comments