Computing Check Digits With BigInt
In this lesson, you ported the line that computes each invoice’s RF creditor reference: RF, two
check digits, and the reference, which is the customer number and the month. Python works out the
check digits in one line, 98 - int(reference + "271500") % 97, on a 17-digit int, and Larder
Lane’s reference is RF9140417202610.
- Ported with
Number()forint(), the line runs and printsRF8740417202610, where Python printsRF9140417202610. The 17-digit number is past2 ** 53, so it isn’t exact: it logs as40417202610271500, but the number it holds is40417202610271504,Number.isSafeInteger()saysfalse, and its remainder after 97 is 11, where Python’s is 7. - BigInt is JavaScript’s exact integer of any size.
BigInt("40417202610271500")builds one from text, the wayint()does, and prints as40417202610271500n. typeofanswers"bigint"for it, and BigInts have the same+,-,*,%and comparisons as numbers.- Build BigInts from text, not from a number:
BigInt(order.id)after a plainJSON.parse()keeps only the rounded ID. - With
BigInt()forint(), the line stops withTypeError: Cannot mix BigInt and other types, use explicit conversions, at the remainder. - Python’s 98 and 97 are ints, but in JavaScript a plain
97is a number, the counterpart of Python’s float. In Python, an int mixed with a float becomes a float, and with97.0the line gives87.0, the wrong digits again. Turning a BigInt into a number would lose digits, and turning a number into a BigInt would lose any fraction, so JavaScript never combines the two in arithmetic: you choose. - An
nafter the digits writes a BigInt literal, and the fix gives every literal one:98n - (BigInt(reference + "271500") % 97n)is91n. The parentheses don’t change the order, since%comes first anyway. A template literal prints a BigInt without then. - Python’s
:02dbecomesString(check)with a"0"in front whencheck < 10n. Bluebell Café’s November check is8n, printed as08.===never calls a BigInt and a number equal:91n === 91isfalse, where Python’s91 == 91.0isTrue, so compare with91n. - Use BigInt where Python’s int goes past
2 ** 53and the digits matter. Keep the whole calculation in BigInt, and convert at the edges. Everywhere else, a number is still the right type: BigInt has no fractions, so/drops the remainder, and theMathfunctions take numbers only.
Here’s the finished port of the reference lines:
const INVOICE_MONTH = "202610";
function rfReference(reference) {
const check = 98n - (BigInt(reference + "271500") % 97n);
let digits = String(check);
if (check < 10n) {
digits = "0" + digits;
}
return `RF${digits}${reference}`;
}
console.log(rfReference("40417" + INVOICE_MONTH));
console.log(rfReference("40422" + INVOICE_MONTH));
console.log(rfReference("40436" + INVOICE_MONTH));
console.log(rfReference("40422" + "202611"));