From b4c4eafd956cb5691c0f135b7152f32a3293f19f Mon Sep 17 00:00:00 2001 From: lovegupta112 Date: Tue, 29 Aug 2023 13:45:58 +0530 Subject: [PATCH] created reduceFunction --- reduce.js | 38 ++++++++++++++++++++++++++++++++++++++ test/testReduce.js | 14 ++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 reduce.js create mode 100644 test/testReduce.js diff --git a/reduce.js b/reduce.js new file mode 100644 index 0000000..930578b --- /dev/null +++ b/reduce.js @@ -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