实现说明
活动部件是函数 looksHex。
使用要点
- 直接运行文件,输出会带上标签,比如
valid:、invalid zz:、mixed 48zz6c:——输出的每一行都能指回产生它的那次调用。
常见问题
有第三方依赖吗?
没有。依赖清单是空的,代码只用标准库。 文件在加载时定义 looksHex。
入口签名:const looksHex = (value)
核心语句
const looksHex = (value) => /^[0-9a-f]+$/i.test(value) && value.length % 2 === 0;
代码示例
// Buffer.from(data, 'hex') parses leading valid byte pairs and silently
// stops at the first invalid character pair — no error is thrown.
console.log('valid:', Buffer.from('48656c6c6f', 'hex').toString());
console.log('invalid zz:', JSON.stringify(Buffer.from('zz', 'hex').toString()), 'length:', Buffer.from('zz', 'hex').length);
console.log('mixed 48zz6c:', JSON.stringify(Buffer.from('48zz6c', 'hex').toString()));
console.log('odd tail 486:', JSON.stringify(Buffer.from('486', 'hex').toString()), 'length:', Buffer.from('486', 'hex').length);
// For untrusted input, validate the shape before decoding: a strict regex
// plus an even-length check catches corruption the decoder glosses over.
const looksHex = (value) => /^[0-9a-f]+$/i.test(value) && value.length % 2 === 0;
console.log('checksum ok:', looksHex('48656c6c6f'), 'rejected:', looksHex('48zz'));
// Re-encoding the decoded bytes round-trips only when the input was fully
// valid, which makes the silent truncation visible in tests.
const reencoded = Buffer.from('48656c6c6fzz', 'hex').toString('hex');
console.log('re-encoded:', reencoded, 'round-trips:', reencoded === '48656c6c6fzz');