Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Write a function addThreeNumsFromString that takes a single string
- * as argument. The given string will consist of three numbers
- * separated by a space. The function will add the three the numbers
- * and return their sum.
- */
- /* This is the high-level view of what's going wrong with this
- * program.
- */
- console.log(addThreeNumsFromString("5 5 5"))
- // will log 15
- console.log(addThreeNumsFromString("4 2 1"))
- // will log 7
- //Your Answer:
- var sum = 0;
- function addThreeNumsFromStringWrong(str) {
- var newArr = str.split("");
- for (var i = 0; i < str.length; i++) {
- sum += newArr[i];
- }
- return sum;
- }
- // Your approach, just debugged.
- function addThreeNumsFromStringOne (str){
- let sum = 0;
- // Split at the spaces to remove them.
- let newArr = str.split(" ");
- for (let i = 0; i < newArr.length; i++) {
- sum += Number(newArr[i]);
- }
- return sum;
- }
- /* Also similar to your approach, but using the forEach function means
- * you have less of a chance to mess up.
- */
- function addThreeNumsFromStringTwo(str) {
- let sum = 0;
- let newArr = str.split(" ");
- newArr.forEach((number) => {
- sum += Number(number);
- })
- return sum;
- }
- /* Since the first approach was so close to just being functional,
- * let's take this all the way: a full functional approach.
- */
- function addThreeNumsFromStringThree {
- return str.split(" ").map(Number).reduce((sum, value) => sum + value);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement