HackerRank - 10 Days JavaScript Challenge
So I took on the HackerRank 10 Days Challenge for practice, it covered a pretty wide range of topics for such few questions
Basic JavaScript
Data Types and Manipulation
parseInt() - make integer
parseFloat() - make float
String() - make string, strings can be concatenated using +
Loops
for & while loops
do - while loops
for - in loops
for - of loops
For Loop
While Loop
Do-while Loop
For In Loop
For Of Loop
Loop over char of String, Extract Vowels & Consonants
First, print each vowel in on a new line. The English vowels are a, e, i, o, and u, and each vowel must be printed in the same order as it appeared in .
Second, print each consonant (i.e., non-vowel) in on a new line in the same order as it appeared in .
Difference between for-in and for-of loops: keys vs values example:
Factorial in JavaScript
Day 3 : Arrays
Task : Given an array, return the second largest integer in the array
Day 3 : Try, Catch and Finally - Strings Manipulation
Strings Basic Manipulation
String.charAt() -
Returns the character at the specified indexString.concat() -
Returns a new string consisting of the calling string concatenated with another string passed as an argument --> string1.concat(string2)String.includes() -
Returns a boolean denoting whether a string passed as an argument exists within the calling string.String.endsWith() -
Returns a boolean denoting whether the calling string ends with the characters of another string passed as an argument.String.indexOf() -
Returns an integer denoting the index within the calling String object of the first occurrence of the given argumentString.lastIndexOf() -
Returns an integer denoting the index within the calling String object of the last occurrence of the given argumentString.match() -
Match a regular expression passed as an argument against the calling string. If a match is found, it returns an object with three properties: the matched substring, theindex
it was found at, and theinput
(i.e., the initial string)String.normalize() -
Returns a string containing the Unicode Normalization Form of the calling string's value.String.repeat() -
Returns a string consisting of the elements of the calling String object repeated some number of times (given as an integer argument). If no argument or a argument are given, then it returns the empty string.String.replace() -
Finds a match between a regular expression and a string, then returns a string where the first matched substring is replaced with a new substring.
String.search() -
Executes the search for a match between a regular expression and a specified string, then returns the index of the first character of the first match.String.slice() - google this
String.split()
String.startsWith() -
Returns a boolean denoting whether a string begins with the characters of another string passed as an argumentString.substr() -
Returns a substring consisting of characters in a given range, depending on the arguments passed to the functionString.toLowerCase() | String.toUpperCase() | String.trim() - trim whitespaces
Try, Catch and Finally Code
https://www.hackerrank.com/challenges/js10-try-catch-and-finally/topics
The try block is the first step in error handling and is used for any block of code that is likely to raise an exception. It should contain one or more statements to be executed and is typically followed by at least one catch clause and/or the optional finally clause. In other words, the try statement has three forms:
try-catch
try-finally
try-catch-finally
The catch block immediately follows the try block and is executed only if an exception is thrown when executing the code within the try block. It contains statements specifying how to proceed and recover from the thrown exception; if no exception is thrown when executing the try block, the catch block is skipped. If any statement within the try block (including a function call to code outside of the block) throws an exception, control immediately shifts to the catch clause.
The finally block is optional. It executes after the try and catch blocks, but before any subsequent statements following these blocks. The finally block always executes, regardless of whether or not an exception was thrown or caught.
Task: Reverse String with Try, Catch, Finally
Complete the reverseString function; it has one parameter, . You must perform the following actions:
Try to reverse string 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.
Day 3 : Throw and Catch
The theory lesson
Errors “indicates serious problems that a reasonable application should not try to catch.” This refers to problems that the application can not recover from - they should be dealt with by modifying application architecture or by refactoring code. Exceptions, on the other hand, indicate “conditions that a reasonable application might want to catch.” These could include problems that can occur at compile-time (checked exceptions) or run-time (unchecked exceptions) and can happen rather frequently in most applications
When we develop something, we often need our own error classes to reflect specific things that may go wrong in our tasks. For errors in network operations we may need HttpError
, for database operations DbError
, for searching operations NotFoundError
and so on.
Our errors should support basic error properties like message
, name
and, preferably, stack
. But they also may have other properties of their own, e.g. HttpError
objects may have a statusCode
property with a value like 404
or 403
or 500
.
JavaScript allows to use throw
with any argument, so technically our custom error classes don’t need to inherit from Error
. But if we inherit, then it becomes possible to use obj instanceof Error
to identify error objects. So it’s better to inherit from it.
As the application grows, our own errors naturally form a hierarchy. For instance, HttpTimeoutError
may inherit from HttpError
, and so on.
2. Back to the question
There are 2 ways to throw an error:
We can throw an exception by following the keyword
throw
with some that we wish to use for the exception being thrown.We can throw an exception by following the keyword
throw
withnew Error(customError)
, where customError is the value we want for the message property of the exception being thrown ( TLDR: USE new Error() for custom errors)
3. HackRank Question
Complete the isPositive function below. It has one integer parameter, a . If the value of a is positive, it must return the string YES
. Otherwise, it must throw an Error according to the following rules:
If a ==0 , throw an Error with
Zero Error
.If a is negative, throw an Error with
Negative Error
.
Day 4 : Objects Basics
Theory Lesson : Objects
We define the following:
Object: A collection of properties.
Property: An association between a name (i.e., key) and a value. Note that when the value associated with a key is a function, we call the property a method. A property name can be any valid string, or anything that can be converted into a string (including the empty string).
An object has properties associated with it, and we explain an object's properties as variables that are part of the object. We can think of an object's properties as a set of regular variables specific to that object that define its characteristics.
Let's say we have an object named and a property named . We can access this property in the following ways:
Dot Notation: Call
objectName.propertyName
.Bracket Notation: Call
objectName['propertyName']
. Note that must be enclosed in string quotes and is case-sensitive. Any property name that's not a valid JavaScript identifier (e.g., starts with a number, contains a space or hyphen, etc.) can only be accessed using bracket notation. This type of notation is also good to use when property names are dynamically determined (i.e., not known until runtime).
2. HackerRank Question
Modelling a rectangle by object creation, with properties of area, perimeter, width and length.
Day 4 : Counting Objects
Theory Lesson (For in, For each)
The for...in statement iterates over the enumerable properties of an object in an arbitrary order, which allows us to execute statements for each distinct property. In the case of an array, the property would be its elements. In the case of an object, that would be its properties.
2. HackerRank question - Iterating over Objects
Complete the function in the editor. It has one parameter: an array, a , of objects. Each object in the array has two integer properties denoted by x and y . The function must return a count of all such objects in array that satisfy o.x == o.y.
In my method I used the standard iteration of objects[i].x or objects[i].y.
Alternative methods from the forums
Last updated