如何用hashids.js库编码64位ID?需兼容32位ID且无法换库
解决hashids.js编码64位ID返回空的问题
可以用hashids.js编码64位ID,问题根源在于JavaScript的Number类型有精度上限(2^53 - 1),你的64位ID(如191051377965797390)已经超出这个范围,直接传入数字会导致精度丢失,最终让hashids返回空字符串。以下是两种兼容存量32位ID的可行方案:
方案1:升级hashids.js并使用BigInt
hashids.js的新版本已支持BigInt类型,直接传入字符串转成的BigInt即可规避精度问题,同时完全兼容原有32位ID的编码/解码逻辑:
const Hashids = require('hashids'); // 保留你原有的盐值和配置初始化 const hashids = new Hashids('your-salt-here'); // 编码64位ID:用BigInt包裹字符串形式的ID const bigId = BigInt('191051377965797390'); const hash = hashids.encode(bigId); // 解码:结果返回BigInt,转成字符串即可还原 const decoded = hashids.decode(hash); console.log(decoded[0].toString()); // 输出191051377965797390 // 存量32位ID依然可以正常使用 const old32BitId = 123456; const oldHash = hashids.encode(old32BitId); console.log(hashids.decode(oldHash)); // 输出[123456]
方案2:拆分64位ID为两个32位整数(兼容旧版本hashids)
如果无法升级库,可以把64位ID拆分为高32位和低32位两个整数分别编码;解码时再合并,同样不影响存量32位ID的处理:
const Hashids = require('hashids'); const hashids = new Hashids('your-salt-here'); // 拆分64位ID为高、低32位 function splitId(idStr) { const id = BigInt(idStr); const low32 = id & BigInt(0xFFFFFFFF); const high32 = id >> BigInt(32); return [Number(high32), Number(low32)]; } // 合并高、低32位为64位ID function mergeIds(high, low) { return (BigInt(high) << BigInt(32)) | BigInt(low); } // 编码64位ID const idStr = '191059128930537487'; const [high, low] = splitId(idStr); const hash = hashids.encode(high, low); // 解码 const decodedParts = hashids.decode(hash); const decodedId = mergeIds(decodedParts[0], decodedParts[1]); console.log(decodedId.toString()); // 输出191059128930537487 // 存量32位ID处理:高32位为0,编码解码均正常 const oldId = 789012; const oldHash = hashids.encode(0, oldId); const [oldHigh, oldLow] = hashids.decode(oldHash); console.log(mergeIds(oldHigh, oldLow).toString()); // 输出789012
内容的提问来源于stack exchange,提问作者badrik patel
相关产品推荐
相关产品推荐

