The "problem" I see with this is that not only are you overloading with variadic arguments, you're overloading argument types as well. The combination leads to a messy implementation which only hurts you in the long run.
Here's a different way to write it that uses an auxiliary function, but you're still in for a world of pain (more below).
function fn(...args) {
function aux(str, arr, obj) {
// this function will always have str, arr, and obj
}
// Warning: this has an error anyway because (typeof []) is also 'object'
switch (args.length) {
case 1: return typeof args[0] === 'object'
? aux(null, null, args[0])
: aux(args[0], null, null);
case 2: return typeof args[0] === 'object'
? aux(args[0], null, args[1])
: aux(args[0], args[1], null);
case 3: return aux(args[0], args[1], args[2]);
}
}
With the above implementation, you have 5 unique ways to call your function, all of which are intended to be acceptable and appropriate.
Cons
- Hard-to-memorize API - which result will I get based on which arguments? When I pass a string and an object, which one do I pass first? etc.
- Refactor nightmare - If the function ever needs to change, you need to support all 5 varieties of calls. Once you've forced all 5 behaviours through a single function api, there's no way to separate behaviours without breaking existing code written against this function.
- Unusually complicated boiler plate in function definition - Most functions just map arguments to their local parameters and that's all taken care of for you by JavaScript itself. Your function now has a bunch of code change the way JavaScript behaves, and your code readability suffers because of it. This boilerplate will be multiplied for each function you write with this sort of "design".
- Hard-to-detect types -
typeof [] will return 'object' not 'array' like you might be thinking. You're going to have to write tons of corner cases to ensure you're detecting all of your types correctly. JavaScript is not a typed language, and therefore trying to negotiate behaviour based on typeof as your go-to detection mechanism is going to lead to all sorts of headaches. All this extra code means more probability for bugs, more code to maintain, and the overall quality of your software will ultimately suffer.
Pros
- this section intentionally left blank
Developers often make the mistake that because a language permits a certain way of thinking, that whatever code they come up with, as long as it compiles/executes, that it's OK.
This is a very big misconception, and often why experienced developers appreciate/favour a language with more strictness and more limitations.
Anyway, good luck.
if (typeof args[1] == 'object') { obj = args[1]; } else { arr = args[1]; }, sincetypeofan Array is also'object'.