Task: write a function, the argument of which is a number (can be both fractional and integer), and the result is the sum of all digits

сal(123) = 1+2+3 = 6 cal(123.45) = 1+2+3+4+5 = 15 

The catch is that you cannot use any methods, cycles. Only recursion. Maybe there is someone who knows the solution?

Closed due to the fact that the participants are not on topic with overthesanity , Air , LFC , freim , humster_spb 12 Apr at 12:00 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • " Learning tasks are allowed as questions only on the condition that you tried to solve them yourself before asking a question . Please edit the question and indicate what caused you difficulties in solving the problem. For example, give the code you wrote, trying to solve the problem "- overthesanity, Air, LFC, freim, humster_spb
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • Is this exactly JavaScript? Can you describe the condition of the problem and its intended answer in your own words? - Sergey Nudnov
  • Yes of course. The argument is a number (it can be both fractional and integer), when the function is started it must return the sum of all numbers (cal (123) = 1 + 2 + 3), the solution condition is that no methods and cycles can be used (for, reduce and all that is in js is called with ()). - Oleksandr Tatarinov
  • Something I can not imagine a solution without brackets ... - Alexey Ten

3 answers 3

And the casket just opened ...

 console.log(cal(123.45)) console.log(cal()) console.log(cal('abcd')) console.log(cal('abcd123.45')) function cal(value, index=0) { var result = 0; var value_text = value + ""; //преобразуем в строку var skip = index === value_text.length; //признак пропуска вычислений var digit_text = skip? "." : value_text[index]; //очередная цифра в виде строки index += 1; //result += digit_text >= '0' && digit_text <= '9'? digit_text - '0' : 0; //Не могу удержаться не использовать красивое преобразование от @Stranger in the Q... result += + digit_text || 0; result += skip? 0 : cal(value_text, index); //рекурсия для следующего индекса return result; } 

    brackets are still used to call recursion ...

     let cal = a => { // преобразуем входной аргумент в массив символов если это число a = a > 0 ? [...a + ''] : a; // приводим к числу последний символ массива или берем 0 если символ не приводится к числу let b = + a[a.length - 1] || 0; // складываем число с результатом вызова этой же функции, // но уже с массивом без последнего символа, пока массив содержит символы return a ? b + cal(--a.length ? a : 0) : 0; } console.log(cal(123.45)); 

    • He-he, but my function does not fall on the lines ... - Sergey Nudnov
    • @SergeyNudnov :) well, it's not difficult to add, but for some reason I did not consider this possibility at night looking. I was more interested in the absence of brackets when calling recursion .. - Stranger in the Q
    • You have a more concise code, although it will not work on IE due to ... But with recursion ... It is a pity that there is no reboot of operators. - Sergey Nudnov
    • @SergeyNudnov I have a feeling that one can formally observe the original condition of the author not to use brackets at all - Stranger in the Q
    • @SergeyNudnov, I also reduced the code + it was noticed that a negative number will return 0, but there is also nothing in the question about this - Stranger in the Q

    If the task is in recursion, then I can offer the following algorithm:

     Если входной параметр - 0, то вернуть 0. Если входной параметр - дробное число > 1, то результат = cal(целая часть)+cal(дробная часть). Если входной параметр - целое число, то результат = остаток от деления на 10 + cal(целая часть от деления на десять). Если входной параметр - дробное число от 0 до 1 (не включительно), то результат = целая часть от умножения на 10 + cal(дробная часть от умножения на десять).