skip to Main Content

I have a function called "Time", it accepts from 0 to 6 arguments.

function Time(year,month,day,hour,minutes,options) {

}

Parameters month, day, hour and minutes cannot be defined if the previous one isn’t defined.

Even if the "options" parameter is optional, if present, it has to be the last parameter.

However, user can define only year and month for example, and then options.

How to avoid the user to have to write this:

var newTimeInstance = Time(2024,06, undefined, undefined, undefined, options {
   fr: {
     // ...
   },
   es: {
     // ...
   }
})

If it’s not possible, is there another way to join options to a function ?

I’ve tried: var newTimeInstance = Time(2024,01).options({ ... }) but then I’m unable to access the other constructor functions in newTimeInstance.

2

Answers


  1. Inconvenient, but you could do:

    function Time(...args) {
      if (args.length === 3) {
        const [year, month, options] = args
        console.log({
          year,
          month,
          options
        })
      }
      // other cases
    }
    
    Time(2024, 4, {
      extra: 'options'
    })
    Login or Signup to reply.
  2. Use Array::reduceRight() to check arguments:

    function Time(year,month,day,hour,minutes,options) {
      [...arguments].reduceRight((r, arg, idx, arr) => {
        if(arg === undefined && arr[idx + 1] !== undefined) throw new Error('An argument cannot be undefined');
      });
    }
    
    Time(2024, 3, undefined); // ok
    Time(undefined, 2); // an error
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search