From 2a5c6d7006c14409b03b896b969b7e1904b48b9e Mon Sep 17 00:00:00 2001 From: Benjamin Gruenbaum Date: Tue, 22 Mar 2016 11:36:05 +0200 Subject: [PATCH] dns: Refactor forEach to map MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 Reviewed-By: Сковорода Никита Андреевич --- lib/dns.js | 36 ++++++++++++++++-------------------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/lib/dns.js b/lib/dns.js index dad4353ea2a5b7..6940c51d29e19b 100644 --- a/lib/dns.js +++ b/lib/dns.js @@ -281,41 +281,37 @@ exports.getServers = function() { exports.setServers = function(servers) { // cache the original servers because in the event of an error setting the // servers cares won't have any servers available for resolution - var orig = cares.getServers(); + const orig = cares.getServers(); - var newSet = []; - - servers.forEach(function(serv) { - var ver = isIP(serv); - - if (ver) - return newSet.push([ver, serv]); - - var match = serv.match(/\[(.*)\](:\d+)?/); + const newSet = servers.map((serv) => { + var ipVersion = isIP(serv); + if (ipVersion !== 0) + return [ipVersion, serv]; + const match = serv.match(/\[(.*)\](:\d+)?/); // we have an IPv6 in brackets if (match) { - ver = isIP(match[1]); - if (ver) - return newSet.push([ver, match[1]]); + ipVersion = isIP(match[1]); + if (ipVersion !== 0) + return [ipVersion, match[1]]; } - var s = serv.split(/:\d+$/)[0]; - ver = isIP(s); + const s = serv.split(/:\d+$/)[0]; + ipVersion = isIP(s); - if (ver) - return newSet.push([ver, s]); + if (ipVersion !== 0) + return [ipVersion, s]; 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 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}]`); } };