Files
baiyue-firstleg/scripts/admin-test-env-modules/iso6346-container-number.mjs

19 lines
775 B
JavaScript

import { createHash } from 'node:crypto'
const LETTER_VALUES = [10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32, 34, 35, 36, 37, 38]
export function iso6346ContainerNumber(seed, ownerCode = 'TST') {
if (!/^[A-Z]{3}$/.test(ownerCode)) throw new Error('ownerCode must contain three uppercase letters')
const serial = String(createHash('sha256').update(String(seed)).digest().readUInt32BE(0) % 1_000_000)
.padStart(6, '0')
const body = `${ownerCode}U${serial}`
let sum = 0
for (let index = 0; index < body.length; index += 1) {
const code = body.charCodeAt(index)
const value = code >= 48 && code <= 57 ? code - 48 : LETTER_VALUES[code - 65]
sum += value * (2 ** index)
}
return `${body}${(sum % 11) % 10}`
}