Week day text - JavaScript (Basic) certification test solution | HackerRank



Implement the function weekdayText such that:
  • It takes a single argument, weekdays, which is an array of stings.
  • It returns a new function that called getText that takes single integer argument, number, and does the following:
    • It returns the value from the weekdays array at that 0-based index number.
    • If number is out of range, the function throws an Error object with the message of "Invalid weekday number".
For example, calling weekdayText(["Mon","Tue","Wed","Thur","Fri","Sat","Sun"]) must return a unction getText, such that calling getText(6) return "Sun". "Sun" is at index 6 in the array.

The implementation will be tested by a provided code stub and several input files that contain parameters. The weekdayText function will be called with the weekdays parameter, then the returned function will be called with the number parameter. The result of the latter call will be printed to the standard output by the provided code.


Solution:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
function weekdaysText(weekdays) {
    let day = '';
    return function getText(target) {
        if (target > weekdays.length || target < 0) {
            return 'Invalid day number';
        } else {
            for (let i = 0; i < weekdays.length; i++) {
                day = weekdays[target];
            }
            return day;
        }
    }
}

const day = weekdaysText(['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'])(3);
console.log(day);
Labels : #hackerrank ,#hackerrank certification ,#javascript (basic) ,

1 comment

  1. https://share.anysnap.app/fGZc9ZDLAruE - what is use of this for loop here instead we can get the value just with weekdays[target] right