From a1b2c2176729a92009b9fc6e75a91055cc4c846e Mon Sep 17 00:00:00 2001 From: lion Date: Sun, 19 Oct 2025 23:05:15 +0800 Subject: [PATCH 1/2] optimize the ipv6 bytes to string --- binding/javascript/package.json | 2 +- binding/javascript/util.js | 21 ++++++++++++++++----- 2 files changed, 17 insertions(+), 6 deletions(-) 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; } From a30d9222258dec0b7b2d78030216499a0edf6ab5 Mon Sep 17 00:00:00 2001 From: lion Date: Sun, 19 Oct 2025 23:07:00 +0800 Subject: [PATCH 2/2] lines merge --- binding/javascript/util.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/binding/javascript/util.js b/binding/javascript/util.js index 8545c42..5243313 100644 --- a/binding/javascript/util.js +++ b/binding/javascript/util.js @@ -176,8 +176,7 @@ function _ipv6_to_string(v6Bytes, compress) { } // auto compression of consecutive zero - let mi = ps.length - 1; - let _ = []; + let _ = [], mi = ps.length - 1; for (i = 0; i < ps.length; i++) { if (i >= mi) { _.push(ps[i]);