Skip to content

Commit

Permalink
created reduceFunction
Browse files Browse the repository at this point in the history
  • Loading branch information
Lovegupta112 committed Aug 29, 2023
1 parent 0abdc63 commit b4c4eaf
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
38 changes: 38 additions & 0 deletions reduce.js
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;
14 changes: 14 additions & 0 deletions test/testReduce.js
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);

0 comments on commit b4c4eaf

Please sign in to comment.