JSFiddle - React, Tailwind, and code Playground
by Nithi Nadar
JavaScript
/**
* Month names function
*
* Using a closure, write a function that will
* return the Month name for a given number (1-12).
*
* Hint: Your function will include an array of month names
* Hint: It will return a function
*
*/
function GetMonthNameMethod()
{
var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
return function(i)
{
if (i<1 || i>12)
throw "Invalid month id passed";
return months[i-1];
};
};
var MonthNameRetriver = GetMonthNameMethod();
console.log(MonthNameRetriver(5));
console.log(MonthNameRetriver(12));
console.log(MonthNameRetriver(1));
//console.log(MonthNameRetriver(13)); this will throw exception
/**
* Bonus:
*
* Set a timer to run your function 12 times, once each second
* It should use the increment of a loop to log the month name
* that maps to the integer value
*
* Example output, one line per second:
* "January"
* "February"
* "March"
* ...
*
* Hint: You'll use setTimeout(function, i*1000);
* Hint: You'll need an additional scope to pass "i" correctly
* in to the timer function
*/
for(var i=1;i<=12;i++)
{
// by including the function with "(" and ")", we declaring an expression
(
function(i)
{
setTimeout(function(){console.log(MonthNameRetriver(i));}, 500*i);
}(i)
);
}
//another way... (Comment the above block before running the following)
// This time we have removed the "(" and ")" around the anonymous function. We declared a NamedMethod and
// calling it directly. Earlier we declared anonymous method and called it immediately.
for(var i=1;i<=12;i++)
{
function NamedMethod(i)
{
setTimeout(function(){console.log(MonthNameRetriver(i));}, 500*i);
};
NamedMethod(i);
}