Day 5: Arrow Functions in JavaScript | 10 Days Of JavaScript

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

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

Day 5: Arrow Functions in JavaScript

Table Of Contents 👊

Objective

In this challenge, we practice using arrow functions. 

Task

Complete the function in the editor. It has one parameter: an array, nums. It must iterate through the array performing one of the following actions on each element:

  • If the element is even, multiply the element by 2.
  • If the element is odd, multiply the element by 3.

The function must then return the modified array.

Input Format

The first line contains an integer, n, denoting the size of nums.

The second line contains n space-separated integers describing the respective elements of nums.

Constraints

  • 1 <= n <= 10
  • 1 <= numsi <= 100, where numsi is the ith element of nums.

Output Format

Return the modified array where every even element is doubled and every odd element is tripled.

Sample Input 0

5
1 2 3 4 5

Sample Output 0

3 4 9 8 15

Explanation 0

Given nums = [1, 2, 3, 4, 5], we modify each element so that all even elements are multiplied by 2 and all odd elements are multipled by 3. In other words, [1, 2, 3, 4, 5] = [1*3, 2*2, 3*3, 4*2, 5*3] = [3, 4, 9, 8, 15]. We then return the modified array as our answer.

Solution - Day 5: Arrow 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++];
}

function modifyArray(nums) {
    const func = nums.map(function (num){
        if (num % 2 == 0){
            return 2 * num;
        } else {
            return 3 * num;
        }
    });
    return func;
}


function main() {
    const n = +(readLine());
    const a = readLine().split(' ').map(Number);
    
    console.log(modifyArray(a).toString().split(',').join(' '));
}

Disclaimer: The above Problem (Arrow 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