Reputation: 39
I call the function with and without a parameter. I don't know how to unite them into one. Thanks for help.
Function1
normalizeTime(time) {
var date = new Date(time * 1000);
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
},
Function2
getAmPmTime() {
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
},
Upvotes: 0
Views: 79
Reputation: 20016
You could check whether there is a parameter or not within the function. Sample implementation:
normalizeTime(time) {
var date = time ? new Date(time * 1000) : new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
Upvotes: 2
Reputation: 200
Try using default parameter like this:
joinedFunction(time = null){
var date = time ? new Date(time * 1000) : new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
if you do not pass anything(or a falsy parameter), it will be the same as calling your getAmPmTime
function and if you pass a time, it will be the same as calling your normalizeTime
function.
Upvotes: 1
Reputation: 1072
What about conditionally check if 'time' is available? inside your function:
let date = null;
if (time) {
date = new Date(time * 1000);
} else {
date = new Date();
}
This way, if the function is called without any arguments, a new date object will be created. If not, it will set the date with the time argument.
Upvotes: 3