Skip to content

Instantly share code, notes, and snippets.

@fordmadox
Created June 19, 2014 01:38
Show Gist options
  • Save fordmadox/0a1efa9f96f75d8e06e1 to your computer and use it in GitHub Desktop.
Save fordmadox/0a1efa9f96f75d8e06e1 to your computer and use it in GitHub Desktop.
xquery version "3.0";
declare namespace mdc = "http://mdc";
declare function mdc:add-check-digit-to-partial-barcode ($partial-barcode as xs:string) as xs:string {
(: the next two variables compute the Codabar barcode sum for 14-digit library barcodes according to the Luhn algorithm:)
let $barcode-sum :=
(: add up the even sequence :)
sum(string-to-codepoints($partial-barcode)[position() mod 2 eq 0] ! xs:integer(codepoints-to-string(.)))
+
(: add up the odd sequence :)
sum(string-to-codepoints($partial-barcode)[position() mod 2 eq 1] !
(if (xs:integer(codepoints-to-string(.)) >= 5)
then xs:integer(codepoints-to-string(.)) * 2 - 9
else xs:integer(codepoints-to-string(.)) * 2))
let $check-digit := if ($barcode-sum mod 10 = 0) then 0 else 10 - $barcode-sum mod 10
return concat($partial-barcode, $check-digit)
};
(: check digit returned should be 6 :)
mdc:add-check-digit-to-partial-barcode('3900204393039')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment