Friday, June 11, 2021

Javascript Practice 74: JS Hero - String: split()

 
Question: 

Write a function add that takes a string with a summation task and returns its result as a number. A finite number of natural numbers should be added. The summation task is a string of the form '1+19+...+281'.

Example: add('7+12+100') should return 119.




Answer: 

function add (str) {

const red = (acc, cv) => acc + cv; 
let abcd = str; 
let cdef = abcd.split('+').map(Number); 

return cdef.reduce(red); 





> we declare a function 'add'
> it has 1 parameter 'str' 
> we first declare a variable to use in the reduce method and call it 'red' 
> it basically stores the accumulated value of the array elements which are numbers 
> we then declare a variable 'abcd' which will be the string
> we then convert that string into an array object and use the map method to convert it to a number
> we store that output in a variable 'cdef' 
> we then reduce the 'cdef' variable to a single number by using the reduce method  
> we use the function 'red' along with reduce method
> we return that statement to get our answer

No comments:

Post a Comment