What steps can I take to streamline this code and enhance its elegance in writing?

Working on some practice problems involving higher-order functions, I managed to solve this particular problem. However, the code I used feels somewhat messy and not as elegant as it could be. Is there a better way to combine map and reduce for a cleaner solution? In addition, are there any other methods or optimizations that could have been employed here? Seeking feedback to improve my skills further.

Here is the problem: Given a number, the function "sumDigits" returns the sum of all its digits. If the number is negative, the first digit should be treated as negative.

function sumDigits(num) {

  // Create an array of number characters
  var string = num.toString().split('');

  // If the first character is a negative symbol, make the first numeric element negative
  if (string[0] === "-") {
    string[1] = '-' + string[1];
    string.shift();
  }

  // Convert the string to integers
  var toInteger = string.map(function(x) {
    return Number(x);
  });

  // Get the sum 
  return toInteger.reduce(function(sum, current) {
    sum += current;
    return sum;
  })
}

sumDigits(-316);

Answer №1

Why bother using map when you can simply convert to a number within the reduce function? In my solution, I opted for using the unary + operator to transform the string into a number instead of relying on the Number constructor. This approach may not be superior to using the Number constructor, but it's just a personal preference:

function calculateSumDigits ( num ) {
    const characters = num.toString( ).split( '' );

    // Adjust for negative number if applicable
    // Subtracts first digit twice as it is included in the sum
    return ( characters[0] === '-' ? -2*characters[1] : +characters[0] ) +
      characters.slice( 1 ).reduce( (sum, value) => sum + +value, 0 )
    ;
}

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

Building nested components with Vue.js involves creating a complex routing structure within the architecture

Utilizing vue.js for my administration app, I aim to create a highly modular UI architecture. Therefore, I have structured and enclosed the Header, Body, Sidebar, and Main in single file components as illustrated below. Tree App - Header - dynamic cont ...

Strategies for Effectively Managing Null Checks in Your JavaScript Project

When retrieving data from the BE API, it is in the format: { "details": { "address": { "street": "123/4", "city": "Banglore" } } } In our React project, we access this dat ...

What is the best way to dynamically add a class to the right navigation element in Vue.js when the :class binding only accepts boolean values?

My issue involves implementing a fixed navigation bar with the following structure: <nav class='navigation'> <div :class="{ active: }" @click='scrollTo(".test1")'></div> <div :class=" ...

The UseEffect function ceases to function properly upon refreshing the website

I'm currently using ReactJS for a project. I have a form that is intended to serve as the configuration for another form. The structure of this specific form is as follows: const [startingDate, setStartingDate] = useState(); const [endingDate, set ...

Avoiding the selection of HTML canvas objects

I am currently working on customizing my homepage with an interactive animation. However, I am facing some challenges in integrating it seamlessly into the page. You can view the progress at . My main issue is preventing the canvas object from being select ...

What is the best way to upload a file to a server while working with Vue.js in the Filemanager plugin, or how can I access a global function

How can I upload a file to the server using Vue.js in the Filemanager plugin? I have tried multiple methods and the console log shows that the upload was successful, but I am not able to see any files on the server. Does anyone know what could be wrong? & ...

Retrieve and save files under a common directory

I have a specific route called payments/transactions that retrieves all relevant data. I'm interested in finding a way to generate a CSV file without the need to create new routes or add query parameters, so that my route appears as payments/transacti ...

When submitting the form for the zip code input, use an XMLHttpRequest to input the zip code and retrieve the corresponding city

I'm currently working on a project that involves inputting zip codes and retrieving the corresponding city information from . In the future, I plan to parse this data and store it as variables in my program while potentially using longitude/latitude f ...

How can I display JSON data as key-value pairs in ReactJS?

Transitioning from JavaScript to React, I've come across some threads that touch on this topic but none quite hit the mark. I have a local JSON file that was created with a Python script, and it looks something like this: [{"hello": 10, "world": 15 ...

Strategies for managing asynchronous forEach loops, inserting outcomes into a database, and displaying the finalized dataset

I want to achieve the following steps: Call an API resource Receive an array of records - [arr] Iterate over [arr] and execute a function which involves making another async call to an API for each item Create an object for each iteration that includes el ...

Incorrectly aligned highlighted labels are appearing on the Kendo chart category axis item labels

My current project involves using the kendo chart to generate charts, and I need specific labels to show up as bold text. To achieve this, I am utilizing the visual method which allows me to customize labels and render them with createVisual(). However, w ...

What is the most effective method for combining data from two APIs into a single React table?

Looking to combine data from 2 separate APIs that both have pagination capabilities. What is the most efficient method to present the merged data in a table? The data needs to be joined based on their unique id, however one API provides fewer records tha ...

Tips for integrating v-virtual-scroll with v-table?

My Vuetify table is handling a large amount of data – 300 rows with 20 columns, some of which have calculated rowspans. To improve performance, I'm considering using the v-virtual-scroll component. I came across this sample code, which doesn't ...

Disappearing a menu list while zooming in on a page: The art of vanishing navigation

[QUESTION] Is there a way to make the Menu List disappear when zooming in on a webpage? For example: <-- Normal Page [No Zoom] --> [Logo] Profile Gallery Guestbook <-- Zoom In 120% --> [Logo] Profile Guestbook <-- Zoom In 150% --> ...

When integrating react-hook-form with Material-UI TextField in a form, an error occurs stating that "TypeError: e.target is undefined" when

Hey there, I stumbled upon something fascinating and could really use some assistance. Every time I attempt to perform an onChange, I run into the following error: TypeError: e.target is undefined. Here's a snippet of my setup: import React, { useE ...

`The console is displaying incorrect results when returning a JSON object`

Need to extract the full address as well as the lat and long values from the provided JSON data. var place = { "address_components": [{ "long_name": "17", "short_name": "17", "types": [ "street_number" ] }, ... ...

Streamline email error management within nested middleware functions

I have implemented an express route to handle password resets, which includes finding the user and performing some error handling. However, I am now faced with the challenge of adding additional error handling within a nested function, and I am uncertain a ...

JavaScript only collapsible navigation bar

I have implemented a collapsible navbar using Bootstrap 4 framework according to the documentation provided at this link. The navbar and its contents collapse on small screens, including smartphones, by adding the class .collapse.navbar-collapse. You can ...

"Spin an image using Javascript when it is shown on the

I've got a script that shows an image when we are attacked by a monster. The image is initially set to display="none", but switches to display="" when a monster appears. What I'm looking to do is make the image rotate 360° when it changes from ...

If the request body exists, it should return a 409 error code

*Can anyone please help me with avoiding duplicate requests for existing names in NodeJS Express?* Here is my code: /* Post new person to persons */ app.post("/api/persons/", (req, res) => { const schema = { name: Joi.string().alphanum ...