dns: Refactor forEach to map

Refactor a forEach to a `map` in the `setServers` function of the
dns module - simplifying the code. In addition, use more descriptive
variable names and `const` over `var` where possible.

PR-URL: https://github.com/nodejs/node/pull/5803
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: Сковорода Никита Андреевич <chalkerx@gmail.com>
This commit is contained in:
Benjamin Gruenbaum 2016-03-22 11:36:05 +02:00
parent 03e07d32ac
commit 4985c3411f

View File

@ -285,41 +285,37 @@ exports.getServers = function() {
exports.setServers = function(servers) { exports.setServers = function(servers) {
// cache the original servers because in the event of an error setting the // cache the original servers because in the event of an error setting the
// servers cares won't have any servers available for resolution // servers cares won't have any servers available for resolution
var orig = cares.getServers(); const orig = cares.getServers();
var newSet = []; const newSet = servers.map((serv) => {
var ipVersion = isIP(serv);
servers.forEach(function(serv) { if (ipVersion !== 0)
var ver = isIP(serv); return [ipVersion, serv];
if (ver)
return newSet.push([ver, serv]);
var match = serv.match(/\[(.*)\](:\d+)?/);
const match = serv.match(/\[(.*)\](:\d+)?/);
// we have an IPv6 in brackets // we have an IPv6 in brackets
if (match) { if (match) {
ver = isIP(match[1]); ipVersion = isIP(match[1]);
if (ver) if (ipVersion !== 0)
return newSet.push([ver, match[1]]); return [ipVersion, match[1]];
} }
var s = serv.split(/:\d+$/)[0]; const s = serv.split(/:\d+$/)[0];
ver = isIP(s); ipVersion = isIP(s);
if (ver) if (ipVersion !== 0)
return newSet.push([ver, s]); return [ipVersion, s];
throw new Error(`IP address is not properly formatted: ${serv}`); throw new Error(`IP address is not properly formatted: ${serv}`);
}); });
var r = cares.setServers(newSet); const errorNumber = cares.setServers(newSet);
if (r) { if (errorNumber !== 0) {
// reset the servers to the old servers, because ares probably unset them // reset the servers to the old servers, because ares probably unset them
cares.setServers(orig.join(',')); cares.setServers(orig.join(','));
var err = cares.strerror(r); var err = cares.strerror(errorNumber);
throw new Error(`c-ares failed to set servers: "${err}" [${servers}]`); throw new Error(`c-ares failed to set servers: "${err}" [${servers}]`);
} }
}; };