Reputation: 69
Recently I've been learning node.js, and I've found two code fragments like this:
Fragment 1:
const fs = require('fs')
fs.readFile("content.txt", "utf8", (err, msg) => {
console.log(msg);
})
Fragment 2:
const fs = require('fs')
fs.readFile("content.txt", (err, msg) => {
console.log(msg);
})
They have only one difference that Fragment 1 passed 'utf8' as the second parameter while Fragment 2 skips to pass it. And although they have different results, both of them can function normally without a syntax error.
So I wonder how a javascript method is able to skip to pass the parameter? And how can I define a method/function like this?
Upvotes: 0
Views: 161
Reputation: 1037
With arrow function:
const fn = (...args) => {
console.log(args.length);
if (args.length < 2) {
throw Error('missing arguments');
} else if (args.length === 2) {
/* ... */
} else if (args.length === 3) {
/* ... */
} else {
/* ... */
}
};
or with switch
block
const fn = (...args) => {
console.log(args.length);
switch(args.length) {
case 0: /* ... */ break;
case 1: /* ... */ break;
/* ... */
default: /* ... */ break;
}
};
But it's much better to validate argument type rather than do something depend on args.length
So for your example with the fs
code could look like this:
const readFile = (...args) => {
if (typeof args[0] === 'string') {
/* ... */
} else {
throw TypeError('Path must be a string');
}
if (typeof args[1] === 'string') {
/* ... */
if (typeof args[2] === 'function') {
/* ... */
} else {
throw TypeError('Callback must be a function');
}
} else if (typeof args[1] === 'function') {
/* ... */
} else {
throw TypeError('Callback must be a function');
}
};
readFile({}); // TypeError: path must be a string
readFile('test.txt', 'utf-8', {}); // TypeError: Callback must be a function
readFile('test.txt', {}); // TypeError: Callback must be a function
readFile('test.txt', () => {}); // success
readFile('test.txt', 'utf-8', () => {}); // success
Upvotes: 0
Reputation: 136104
You can achieve this effect in your own code by determining the arity within your method. This might be as simple as just checking the number of arguments, or it might be that you need to check the type of each/some argument(s)
An example:
function myArityAwareFunction(){
if(arguments.length == 2)
console.log("2 arguments", ...arguments)
else if(arguments.length == 3)
console.log("3 arguments", ...arguments)
else
throw ("This method must be called with 2 or 3 arguments");
}
myArityAwareFunction("foo","bar");
myArityAwareFunction("foo","bar","doo");
myArityAwareFunction("This will fail");
Upvotes: 3