JavaScript Quiz – write a one line program to calculate the sum of its digits

This code puzzle could be  asked to frontend engineer or even to experienced web designer.  Given input string of numbers, find the sum of all digits.

Answer could be tricky in programming languages like c or c++ if you have been asked to solve within a single line.

Table of Contents

Solution

input.toString().split("").reduce(function (i, j, key, value) { ni = Number(i); nj = Number(j); return ni + nj });

Explanation

  • Breaking this program logic into pieces.
  • input.toString() It’ll convert input numbers into string.
  • input.toString().split() It’ll convert converted number string into array.
  • input.toString().split().reduce(callback);

    javascript reduce function applies a function against an accumulator and each value of the array (from left-to-right) has to reduce it to a single value.

    i.e. each element from converted array will be passed to this function one by one. return value will be retained as first argument and new value will be second argument. in our case sum will be passed as first argument into reduce function and array element will be second one.

    reduce(function (return_value, array_element, key, value) {
        rv = Number(return_value);
        ae = Number(array_element);
        return rv + ae;
    });
  • Final program in more readable code
    input.toString()
        .split("")
        .reduce(function (i, j, key, value) {
            ni = Number(i);
            nj = Number(j);
            return ni + nj
        });

Demo

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

 
Previous Post

Front-End Engineer in San Francisco – solved code interview questions

Next Post

Tweet post or Facebook like to unlock the content using jQuery

Related Posts