Solutions on Ten Days of JavaScript on HackerRank
Click on below links to see the original question for each topic on HackerRank. Click on below arrows for solution on each question.
- Data Types
Solution
function performOperation(secondInteger, secondDecimal, secondString) {
// Declare a variable named 'firstInteger' and initialize with integer value 4.
const firstInteger = 4;
// Declare a variable named 'firstDecimal' and initialize with floating-point value 4.0.
const firstDecimal = 4.0;
// Declare a variable named 'firstString' and initialize with the string "HackerRank".
const firstString = 'HackerRank ';
// Write code that uses console.log to print the sum of the 'firstInteger' and 'secondInteger' (converted to a Number type) on a new line.
console.log(firstInteger + Number(secondInteger));
// Write code that uses console.log to print the sum of 'firstDecimal' and 'secondDecimal' (converted to a Number type) on a new line.
console.log(firstDecimal + Number(secondDecimal));
// Write code that uses console.log to print the concatenation of 'firstString' and 'secondString' on a new line. The variable 'firstString' must be printed first.
console.log (firstString + secondString);
}
- Arithmetic Operators
- Functions
- Let and Const
Solution
/**
* Calculate the area of a rectangle.
*
* length: The length of the rectangle.
* width: The width of the rectangle.
*
* Return a number denoting the rectangle's area.
**/
function getArea(length, width) {
let area;
area = length * width;
return area;
}
/**
* Calculate the perimeter of a rectangle.
*
* length: The length of the rectangle.
* width: The width of the rectangle.
*
* Return a number denoting the perimeter of a rectangle.
**/
function getPerimeter(length, width) {
let perimeter;
perimeter = 2 * (length + width);
return perimeter;
}
Solution
function factorial (n){
let facNum = 1;
if (n===0)
return 1;
for (let i = n; i >= 1 ; i--)
{
facNum = facNum * i;
}
return facNum;
}
Solution
function main() {
// Write your code here. Read input using 'readLine()' and print output using 'console.log()'.
const PI = Math.PI;
let radius = Number(readLine());
let area = PI * radius * radius;
let perimeter = 2 * PI * radius;
// Print the area of the circle:
console.log(area)
// Print the perimeter of the circle:
console.log(perimeter)
}
- Conditional Statements: If-Else
- Conditional Statements: Switch
- Loops
Solution
function getGrade(score) {
let grade;
// Write your code here
if (score >= 0 && score <=5){
grade = "F"
}
if (score > 5 && score <=10){
grade = "E"
}
if (score > 10 && score <= 15){
grade = "D"
}
if (score > 15 && score <=20){
grade = "C"
}
if (score > 20 && score <=25){
grade = "B"
}
if (score > 25 && score <= 30){
grade = "A"
}
return grade;
}
Solution
function getLetter(s) {
let letter;
let firstChar = s[0];
switch (true){
case ("aeiou").includes(firstChar):
letter = "A";
break;
case ("bcdfg").includes(firstChar):
letter = "B";
break;
case ("hjklm").includes(firstChar):
letter = "C";
break;
default:
letter = "D"
}
return letter;
}
Solution
/*
* Complete the vowelsAndConsonants function.
* Print your output using 'console.log()'.
*/
function vowelsAndConsonants(s) {
const vowels = 'aeiou';
let consonants = '';
for (let i=0; i< s.length; i++)
{
if(vowels.includes(s[i]))
console.log(s[i])
else
consonants = consonants + s[i] + '\n';
}
console.log(consonants.trim());
}
- Arrays
- Try, Catch, Finally
- Throw
Solution
/**
* Return the second largest number in the array.
* @param {Number[]} nums - An array of numbers.
* @return {Number} The second largest number in the array.
**/
function getSecondLargest(nums) {
let s = Array.from (new Set(nums.sort((a,b) => b-a)))
return s[1]
}
Solution
/*
* Complete the reverseString function
* Use console.log() to print to stdout.
*/
function reverseString(s) {
try {
console.log(s.split("").reverse().join(""))
}
catch (e) {
console.log(e.message);
console.log(s)
}
}
Solution
/*
* Complete the isPositive function.
* If 'a' is positive, return "YES".
* If 'a' is 0, throw an Error with the message "Zero Error"
* If 'a' is negative, throw an Error with the message "Negative Error"
*/
function isPositive(a) {
if (a > 0)
{
return "YES"
}
else {
throw (
a === 0 ? new Error ("Zero Error") : new Error ("Negative Error")
)
}
}
- Rectangle Object
- Count Objects
- Classes
Solution
/*
* Complete the Rectangle function
*/
function Rectangle(a, b) {
return {
length : a,
width : b,
perimeter: 2 * (a + b),
area: a *b,
}
}
Solution
/*
* Return a count of the total number of objects 'o' satisfying o.x == o.y.
*
* Parameter(s):
* objects: an array of objects with integer properties 'x' and 'y'
*/
function getCount(objects) {
return objects.filter(o => o.x === o.y ).length
}
Solution
/*
* Implement a Polygon class with the following properties:
* 1. A constructor that takes an array of integer side lengths.
* 2. A 'perimeter' method that returns the sum of the Polygon's side lengths.
*/
class Polygon {
constructor (sides){
this.sides = sides;
};
perimeter(){
let sum =0;
for (let i = 0; i< this.sides.length; i++){
sum = sum + this.sides[i]
}
return sum;
}
}
- Inheritance
- Template Literals
- Arrow Functions
Solution
/*
* Write code that adds an 'area' method to the Rectangle class' prototype
*/
Rectangle.prototype.area = function (){
return this.w * this.h;
}
/*
* Create a Square class that inherits from Rectangle and implement its class constructor
*/
class Square extends Rectangle {
constructor (side){
super (side);
this.w = side;
this.h = side;
}
}
Solution
/*
* Determine the original side lengths and return an array:
* - The first element is the length of the shorter side
* - The second element is the length of the longer side
*
* Parameter(s):
* literals: The tagged template literal's array of strings.
* expressions: The tagged template literal's array of expression values (i.e., [area, perimeter]).
*/
function sides(literals, ...expressions) {
const [a,p] = expressions;
const root = Math.sqrt((p*p) - (16*a))
const s1 = (p + root) / 4
const s2 = (p - root) / 4
return ([s2,s1])
}
Solution
/*
* Modify and return the array so that all even elements are doubled and all odd elements are tripled.
*
* Parameter(s):
* nums: An array of numbers.
*/
function modifyArray(nums) {
return nums.map (n => (n % 2 == 0) ? n * 2 : n * 3)
}
- Bitwise Operators
- JavaScript Dates
Solution
const getMaxLessThanK = function(n, k){
let max_value = 0;
for ( var i = 1 ;i < n ;i++){
for (var j = i+1 ; j < n+1; j++){
if (Number(i & j) < k){
if(Number(i & j) > max_value){
max_value = i & j;
}
}
}
}
return max_value;
}
Solution
// The days of the week are: "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
function getDayName(dateString) {
let dayName;
const date = new Date(dateString);
const options = {
weekday: 'long'
};
dayName = new Intl.DateTimeFormat('en-Us', options).format(date);
return dayName;
}
- Regular Expressions 1
- Regular Expressions 2
- Regular Expressions 3
Solution
function regexVar() {
/*
* Declare a RegExp object variable named 're'
* It must match a string that starts and ends with the same vowel (i.e., {a, e, i, o, u})
*/
let re = /^([aeiou]).*\1$/;
return re;
}
Solution
function regexVar() {
/*
* Declare a RegExp object variable named 're'
* It must match a string that starts with 'Mr.', 'Mrs.', 'Ms.', 'Dr.', or 'Er.',
* followed by one or more letters.
*/
let re = /^(Mr|Mrs|Ms|Dr|Er)(\.)([a-zA-Z])*$/
return re;
}
Solution
function regexVar() {
/*
* Declare a RegExp object variable named 're'
* It must match ALL occurrences of numbers in a string.
*/
let re = /\d+/g;
return re;
}
- Create a Button
- Buttons Container
Solution
See a pen here:
https://codepen.io/juniHub/pen/eYeVWLR
Solution
See a pen here:
https://codepen.io/juniHub/pen/qBVxmoY
- Binary Calculator
Solution
See a pen here:
https://codepen.io/juniHub/pen/XWzZRVg