Advertisement
beelzebielsk

stringToNumber-solutions

Oct 27th, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Write a function addThreeNumsFromString that takes a single string
  2.  * as argument. The given string will consist of three numbers
  3.  * separated by a space. The function will add the three the numbers
  4.  * and return their sum.
  5.  */
  6.  
  7. /* This is the high-level view of what's going wrong with this
  8.  * program.
  9.  */
  10.  
  11. console.log(addThreeNumsFromString("5 5 5"))
  12. // will log 15
  13. console.log(addThreeNumsFromString("4 2 1"))
  14. // will log 7
  15.  
  16.  
  17. //Your Answer:
  18. var sum = 0;
  19.  
  20. function addThreeNumsFromStringWrong(str) {
  21.   var newArr = str.split("");
  22.   for (var i = 0; i < str.length; i++) {
  23.     sum += newArr[i];
  24.   }
  25.   return sum;
  26. }
  27. // Your approach, just debugged.
  28. function addThreeNumsFromStringOne (str){
  29.   let sum = 0;
  30.   // Split at the spaces to remove them.
  31.   let newArr = str.split(" ");
  32.   for (let i = 0; i < newArr.length; i++) {
  33.     sum += Number(newArr[i]);
  34.   }
  35.   return sum;
  36. }
  37.  
  38. /* Also similar to your approach, but using the forEach function means
  39.  * you have less of a chance to mess up.
  40.  */
  41. function addThreeNumsFromStringTwo(str) {
  42.   let sum = 0;
  43.   let newArr = str.split(" ");
  44.   newArr.forEach((number) => {
  45.     sum += Number(number);
  46.   })
  47.   return sum;
  48. }
  49.  
  50. /* Since the first approach was so close to just being functional,
  51.  * let's take this all the way: a full functional approach.
  52.  */
  53. function addThreeNumsFromStringThree {
  54.   return str.split(" ").map(Number).reduce((sum, value) => sum + value);
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement