Day 3: Try, Catch, and Finally Solution
Hello Friends in this article i am gone to share Hackerrank 10 days of javascript solutions with you. | Day 3: Try, Catch, and Finally Solution.
Also visit this link:ย Day 3: Arrays Solution
Day 3: Try, Catch, and Finally Solution
Objective
In this challenge, we learn aboutย stringsย andย exceptions.
Task
Complete theย reverseStringย function; it has one parameter,ย s. You must perform the following actions:
- Tryย to reverse stringย sย using theย split,ย reverse, andย joinย methods.
- If an exception is thrown,ย catchย it and print the contents of the exceptionโsย messageย on a new line.
- Printย sย on a new line. If no exception was thrown, then this should be the reversed string; if an exception was thrown, this should be the original string.
Input Format
Locked stub code in the editor reads variableย sย from stdin and passes it to the function.
Output Format
You must write two print statements usingย console.log():
- Print the contents of a caught exceptionโsย messageย on a new line. If no exception was thrown, this line should not be printed.
- Printย sย on a new line. If no exception was thrown, then this should be the reversed string; if an exception was thrown, this should be the original string.
Sample Input 0
"1234"
Sample Output 0
4321
Explanation 0
sย = โ1234โย is a string type, so it can be reversed without throwing an exception. Thus, we print the reversed value,ย 4321, as our answer.
Sample Input 1
Number(1234)
Sample Output 1
s.split is not a function
1234
Explanation 1
sย = Number(1234)ย is not a string type, so it canโt be reversed using string functions. When weย tryย to reverse it anyway, it throws an exception. We thenย catchย the exception and print itsย message, which isย s.split is not a function. Next, weย finallyย printย sย which, because it wasnโt able to be reversed, isย Number(1234).
Solution โ Day 3: Arrays
'useย strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); letย inputStringย =ย ''; letย currentLineย =ย 0; process.stdin.on('data',ย inputStdinย =>ย { ย ย ย ย inputStringย +=ย inputStdin; }); process.stdin.on('end',ย _ย =>ย { ย ย ย ย inputStringย =ย inputString.trim().split('\n').map(stringย =>ย { ย ย ย ย ย ย ย ย returnย string.trim(); ย ย ย ย }); ย ย ย ย ย ย ย ย main();ย ย ย ย }); functionย readLine()ย { ย ย ย ย returnย inputString[currentLine++]; } /* ย *ย Completeย theย reverseStringย function ย *ย Useย console.log()ย toย printย toย stdout. ย */ functionย reverseString(s)ย { ย ย ย ย tryย { ย ย ย ย ย ย ย ย sย =ย s.split('').reverse('').join(''); ย ย ย ย }ย catch(e){ ย ย ย ย ย ย ย ย console.log("s.splitย isย notย aย function"); ย ย ย ย } ย ย ย ย console.log(s); } functionย main()ย { ย ย ย ย constย sย =ย eval(readLine()); ย ย ย ย ย ย ย ย reverseString(s); }