diff --git a/binding/javascript/package.json b/binding/javascript/package.json index 843ef99..797d3b6 100644 --- a/binding/javascript/package.json +++ b/binding/javascript/package.json @@ -1,6 +1,6 @@ { "name": "ip2region.js", - "version": "3.1.3", + "version": "3.1.4", "description": "official javascript binding for ip2region with both IPv4 and IPv6 supported ", "type": "module", "main": "index.js", diff --git a/binding/javascript/util.js b/binding/javascript/util.js index a8136bb..8545c42 100644 --- a/binding/javascript/util.js +++ b/binding/javascript/util.js @@ -155,20 +155,31 @@ function _ipv4_to_string(v4Bytes) { // ipv6 bytes to string function _ipv6_to_string(v6Bytes, compress) { - let ps = []; + let ps = [], needCompress = false; + let last_hex = -1, hex = 0; for (var i = 0; i < v6Bytes.length; i += 2) { - ps.push(v6Bytes.readUint16BE(i).toString(16)); + hex = v6Bytes.readUint16BE(i).toString(16); + ps.push(hex); + + // check the necessity for compress + if (last_hex > -1 + && hex == 0 && last_hex == 0) { + needCompress = true; + } + + // reset the last hex + last_hex = hex; } - if (compress === false) { + if (needCompress == false || compress === false) { return ps.join(':'); } // auto compression of consecutive zero - let j = 0, mi = ps.length - 1; + let mi = ps.length - 1; let _ = []; for (i = 0; i < ps.length; i++) { - if (i >= mi || j > 0) { + if (i >= mi) { _.push(ps[i]); continue; }