Recientemente estuve aprendiendo node.js y encontré dos fragmentos de código como este:
Fragmento 1:
const fs = require('fs') fs.readFile("content.txt", "utf8", (err, msg) => { console.log(msg); })Fragmento 2:
const fs = require('fs') fs.readFile("content.txt", (err, msg) => { console.log(msg); })Solo tienen una diferencia: el Fragmento 1 pasó 'utf8' como segundo parámetro, mientras que el Fragmento 2 salta para pasarlo. Y aunque tienen resultados diferentes, ambos pueden funcionar normalmente sin un error de sintaxis.
Entonces, me pregunto cómo un método de JavaScript puede omitir para pasar el parámetro. ¿Y cómo puedo definir un método/función como esta?
Puede lograr este efecto en su propio código determinando la aridad dentro de su método. Esto podría ser tan simple como verificar la cantidad de argumentos, o podría ser que necesite verificar el tipo de cada uno de los argumentos.
Un ejemplo:
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");Con función de flecha:
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 { /* ... */ } }; o con bloque de switch
const fn = (...args) => { console.log(args.length); switch(args.length) { case 0: /* ... */ break; case 1: /* ... */ break; /* ... */ default: /* ... */ break; } }; Pero es mucho mejor validar el tipo de argumento en lugar de hacer algo que dependa de args.length
Entonces, para su ejemplo con el código fs , podría verse así:
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