Day 1: Functions in JavaScript | 10 Days Of JavaScript

Hello there, today we are going to solve Day 1: Arithmetic Operators Hacker Rank Solution in JavaScript which is a Part of 10 Days Of JavaScript.

Hello there, today we are going to solve Day 1: Arithmetic Operators Hacker Rank Solution in JavaScript which is a Part of 10 Days Of JavaScript Series.

Day 1: Functions in JavaScript

Table Of Contents 👊

Objective

Today, we're discussing JavaScript functions

Task

Implement a function named factorial that has one parameter: an integer, n. It must return the value of n! (i.e., n factorial).

Input Format

Locked stub code in the editor reads a single integer, n, from stdin and passes it to a function named factorial.

Constraints

  • 1 <= n <= 10

Output Format

The function must return the value of n!.

Sample Input 0

4

Sample Output 0

24

Explanation 0

We return the value of  4! = 4 x 3 x 2 x 1 = 24.

Solution - Day 1: Functions

'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++];
}
/*
 * Create the function factorial here
 */
function factorial(n) {
    if (n < 2){
        return 1;
    }
    return n * factorial(n-1);
}


function main() {
    const n = +(readLine());
    
    console.log(factorial(n));
}

Disclaimer: The above Problem (Functions) is generated by Hacker Rank but the Solution is Provided by Sloth Coders. This tutorial is only for Educational and learning Purpose.

Sloth Coders is a Learning Platform for Coders, Programmers and Developers to learn from the basics to advance of Coding of different langauges(python, Java, Javascript and many more).

Post a Comment