Skip to content

Instantly share code, notes, and snippets.

@thebengeu
Created January 19, 2014 11:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thebengeu/8503349 to your computer and use it in GitHub Desktop.
Save thebengeu/8503349 to your computer and use it in GitHub Desktop.
Calculates correct NUS matriculation number with check digit, given matriculation number with missing / wrong check digit, NUSNET ID or NUS email address, with either U or A prefix.
var calculateNUSMatricNumber = function (id) {
var matches = id.toUpperCase().match(/^A\d{7}|U\d{6,7}/);
if (matches) {
var match = matches[0];
// Discard 3rd digit from U-prefixed NUSNET ID
if (match[0] === 'U' && match.length === 8) {
match = match.slice(0, 3) + match.slice(4);
}
var weights = {
U: [0, 1, 3, 1, 2, 7],
A: [1, 1, 1, 1, 1, 1]
}[match[0]];
for (var i = 0, sum = 0, digits = match.slice(-6); i < 6; i++) {
sum += weights[i] * digits[i];
}
return match + 'YXWURNMLJHEAB'[sum % 13];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment