Having a hard time implementing a subtracting callback function in a JavaScript reduce function

Currently, I am tackling a code challenge in JavaScript that requires me to develop a function called reduce. This function is responsible for reducing a collection to a value by applying a specific operation on each item in the collection over which it iterates. The necessary parameters for this function include the array, callback, and start. If the start parameter is not provided, it defaults to zero.

At present, my implementation looks like this:

function reduce(array, callback, start) {
    if(typeof start === 'number'){
        var initVal = start;
    } else {
        var initVal = 0;
    }
    return array.reduce(callback, initVal);
}

I have a set of tests prepared to evaluate my function, and it appears to be failing only one test that involves a callback function for subtracting values. The specific test causing failure is as follows:

var difference = function(tally, item) {return tally - item; };
var total = reduce([1, 2, 3], difference);
expect(total).to.equal(-4);

I would greatly appreciate any guidance or insights to help resolve this issue.


Update: Here is the revised working solution:

function reduce(array, callback, start) {
    if( typeof start === 'undefined' ){
        return array.reduce(callback);
    } else {
        return array.reduce(callback, start);
    }
}

Answer №1

Your code isn't functioning because you are misusing the start parameter, which should be the index of the initial element.

For example, if you have the input array [1, 2, 3] and are using a subtraction function as a callback, the result you're getting is:

  1. The reducer accumulator is starting at 0 (which is incorrect)
  2. 0 - 1 -> -1
  3. -1 - 2 -> -3
  4. -3 - 3 -> -6

Here is what you should have done instead:

  1. Since no third parameter is passed, the iteration starts from the beginning of the array.
  2. The accumulator is not explicitly initialized, so it takes the first element, giving you acc = 1
  3. 1 - 2 -> -1
  4. -1 - 3 -> -4

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display the chosen alternative in a Bootstrap dropdown menu

I am currently facing an issue with the dropdown list in my bootstrap menu. <li class="dropdown"> <a aria-expanded="false" aria-haspopup="true" role="button" data-toggle="dropdown" class="dropdown-toggle" href="#">Chose option<span class="c ...

Unable to navigate through bootstrap dropdown items using keyboard shortcuts

I am currently working on a bootstrap dropdown menu that is filled with time zone details. Everything seems to be in order as the dropdown gets populated correctly. However, when I click on it and try to select an item by pressing a key on the keyboard (fo ...

Leverage jQuery deferred objects to handle a dynamic amount of AJAX requests

When faced with multiple ajax requests, how can I execute them using deferreds? This is my approach: //qty_of_gets = 3; function getHTML(productID, qty_of_gets){ var dfd = $.Deferred(), i = 0, c = 0; // hypothetical cod ...

Unable to automate the selection of a dropdown menu using Selenium WebDriver

I am currently utilizing http://www.makemytrip.com/ This is the HTML code. <div class="mrgnBot30 clearFix"> <span class="watch_icn flL"></span> <div class="widget_inner clearFix suggest_me padBot15 flL"> <h3 class="clearFix has ...

Turn off the validation of individual JavaScript errors in Eclipse

Currently, I am exploring the use of Eclipse for JavaScript within the "Eclipse IDE for Java EE Developers" package. In my project, there is a heavy reliance on Bluebird, a promises implementation, resulting in several lines like: somePromise.catch(funct ...

Extract branch, path, and URL from the .gitmodules file by utilizing JavaScript Regex

Is there a way to extract branch, path, and URL details from the .gitmodules file using JavaScript Regex? .gitmodules [submodule "PATH"] path = <PATH> url = <URL> [submodule "PATH"] path = <PATH> url = <URL> ...

Accessing the web3 attribute from the React-Web3 provider to enhance functionality

I'm struggling to understand the basic functionality of react-web3-provider My component structure is as follows: import React, { Component } from "react" import { withWeb3 } from 'react-web3-provider'; import Web3 from 'web ...

Creating an interactive star rating system with JSON data

Currently, I am in the process of developing a star rating system specifically designed for restaurant reviews. The 'Attributes' displayed on the user interface are dynamic and fetched in JSON format. There exist five attributes with each having ...

Issue encountered while trying to connect to MongoDB: MongooseServerSelectionError

I am encountering an issue while attempting to establish a connection from my Node.js application to MongoDB using Mongoose. Every time I try to launch the application, I encounter the following error: "Error connecting to MongoDB: MongooseServerSele ...

What is the reason for the initial array elements having matching addresses when compared?

During my work on a project, I encountered a bug in my code that took me quite some time to identify. Upon closer examination, I discovered a peculiar issue that had been causing the problem all along. Oddly enough, the addresses of the initial elements i ...

Nextjs: issue with updating state within an interval is not functioning

This is my current situation: const [time, setTime] = useState(10) And this is the function I'm using: const runTimer = () => { useEffect(() => { const interval = setInterval(() => { console.log(time) if ( ...

Implementation of Oriented Bounding Box (OBB) in THREE

After utilizing the Yuka_OBB implementation to create an oriented bounding box, I have some inquiries about the results achieved: Bed (AABB) https://i.sstatic.net/OgZBU.png Bed (OBB) https://i.sstatic.net/fzOOW.png Wall (AABB) https://i.sstatic.net/R ...

What is the process for transforming pagination numbers into Arabic numerals?

When working with pagination in my project, I have utilized both ant design and material ui. However, I encountered a problem when attempting to change the default Latin numbers to Arabic numbers. Despite trying ant design localization, I was unable to aff ...

When using async functions in iterative processes

In my current setup, I am utilizing a for-each loop to handle a list and specifically require element n to be processed only after element n-1 has completed: let elements = ["item1", "item2", "item3"]; elements.forEach(function(element){ someAsyncFun ...

How to automatically insert a comma into numbers as you type in Vue.js

I am trying to insert separators in my numbers as I type, but for some reason it is not working. Sample Code <el-input-number v-model="form.qty" style="width: 100%;" id="test" placeholder="Quantity" controls-position="right" v-on:keyup="handleChange" ...

Utilize a single submit button to navigate through multiple pages dynamically using JavaScript

I would like to navigate to different rooms with just one button using JavaScript. For instance, there are three rooms: "Kitchen, Toilet, and Bedroom". How can I utilize JS to enter any of these rooms based on my selection? If I input "kitchen" in the text ...

What is the best way to efficiently pass a prop from a Parent styled component to its children's styled components, regardless of how deeply nested they are?

I am utilizing these customized components: import styled, { css } from 'styled-components' const Container = styled.div` background-color: ${props => props.theme === "light" ? "hsl(0, 0%, 98%)" : "hsl(235, 24%, 19% ...

Issue with datepicker initialization causing format not to work in Bootstrap

I am currently incorporating the angular-bootstrap datepicker module into my app and have run into a minor issue. I am using an input text field and a button to display the date in the following manner: <div class="row" id="datePicker"> <p cl ...

How can I adjust the size of the renderer in Three.js to fit the screen?

Encountering issues with the code snippet below: //WebGL renderer renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); //TODO: set optimal size document.body.appendChild(renderer ...

The post page remains out of reach for Ajax

I've been struggling for hours to identify the issue with this code. I realized that I am unable to access the updateuser.php file even though it is in the same directory and the filenames are correct. Can someone please review the code below and let ...