Skip to content

Commit

Permalink
feat: improve stringToHexStripped (#88)
Browse files Browse the repository at this point in the history
  • Loading branch information
Uzlopak authored Jun 14, 2024
1 parent b46ceb2 commit 77165fb
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 5 deletions.
16 changes: 11 additions & 5 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,20 @@ function normalizeIPv4 (host) {
}
}

function stringToHexStripped (input) {
/**
* @param {string[]} input
* @param {boolean} [keepZero=false]
* @returns {string|undefined}
*/
function stringArrayToHexStripped (input, keepZero = false) {
let acc = ''
let strip = true
for (const c of input) {
if (c !== '0' && strip === true) strip = false
if (HEX[c] === undefined) return undefined
if (c !== '0' && strip === true) strip = false
if (!strip) acc += c
}
if (keepZero && acc.length === 0) acc = '0'
return acc
}

Expand All @@ -36,7 +42,7 @@ function getIPV6 (input) {
function consume () {
if (buffer.length) {
if (isZone === false) {
const hex = stringToHexStripped(buffer.join(''))
const hex = stringArrayToHexStripped(buffer)
if (hex !== undefined) {
address.push(hex)
} else {
Expand Down Expand Up @@ -83,7 +89,7 @@ function getIPV6 (input) {
} else if (endIpv6) {
address.push(buffer.join(''))
} else {
address.push(stringToHexStripped(buffer.join('')))
address.push(stringArrayToHexStripped(buffer))
}
}
output.address = address.join('')
Expand Down Expand Up @@ -232,5 +238,5 @@ module.exports = {
removeDotSegments,
normalizeIPv4,
normalizeIPv6,
stringToHexStripped
stringArrayToHexStripped
}
24 changes: 24 additions & 0 deletions test/util.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
'use strict'

const tap = require('tap')
const test = tap.test
const {
stringArrayToHexStripped
} = require('../lib/utils')

test('stringArrayToHexStripped', (t) => {
const testCases = [
[[['0', '0', '0', '0']], ''],
[[['0', '0', '0', '0'], false], ''],
[[['0', '0', '0', '0'], true], '0'],
[[['0', '1', '0', '0'], false], '100'],
[[['1', '0', '0', '0'], false], '1000'],
[[['1', '0', '0', '0'], true], '1000']
]

t.plan(testCases.length)

testCases.forEach(([input, expected]) => {
t.strictSame(stringArrayToHexStripped(input[0], input[1]), expected)
})
})

0 comments on commit 77165fb

Please sign in to comment.