简体   繁体   中英

how to make one of two functions

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;
    },

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.

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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM