Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: improve stringToHexStripped #88

Merged
merged 1 commit into from
Jun 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
})
})
Loading