-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
0abdc63
commit b4c4eaf
Showing
2 changed files
with
52 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
/* | ||
Do NOT use .reduce to complete this function. | ||
How reduce works: A reduce function combines all elements into a single value going from left to right. | ||
Elements will be passed one by one into `cb` along with the `startingValue`. | ||
`startingValue` should be the first argument passed to `cb` | ||
the array element should be the second argument. | ||
`startingValue` is the starting value. If `startingValue` is undefined then make `elements[0]` the initial value. | ||
*/ | ||
|
||
|
||
function reduce(elements, cb, startingValue) { | ||
|
||
let index=0; | ||
|
||
/* we will check if startingValue is undefined so we will start our | ||
loop from index=1 and will use first element of array as starting value | ||
if startingValue is not undefined our loop will start from index=0; | ||
*/ | ||
if(startingValue===undefined){ | ||
|
||
index=1; | ||
startingValue=elements[0]; | ||
} | ||
|
||
let accumulator=startingValue; | ||
|
||
for(;index<elements.length;index++){ | ||
|
||
accumulator=cb(accumulator,elements[index],index); | ||
} | ||
|
||
return accumulator; | ||
} | ||
|
||
module.exports=reduce; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
const reduceFunc=require('../reduce'); | ||
|
||
const items = [1, 2, 3, 4, 5, 5]; | ||
|
||
|
||
function sumFunc(accumulator,curElement,index){ | ||
|
||
console.log("accumulator Current Value : ",accumulator) | ||
return accumulator=accumulator+curElement; | ||
} | ||
|
||
let sumOfArrayElements=reduceFunc(items,sumFunc); | ||
|
||
console.log("Sum of Array's Element: "+sumOfArrayElements); |